Skip to main content

REST with Spring: Quick Start

I used Gradle to run “Hello, World” RESTful web service with Spring.

Requirement

  • JDK 1.8 or later
  • Gradle 4+

1. git clone & cd

git clone https://github.com/spring-guides/gs-rest-service.git
cd gs-rest-service/initial

2. add POJO

src/main/java/com/example/restservice/Greeting.java

package com.example.restservice;

public class Greeting {

	private final long id;
	private final String content;

	public Greeting(long id, String content) {
		this.id = id;
		this.content = content;
	}

	public long getId() {
		return id;
	}

	public String getContent() {
		return content;
	}
}

3. add controller

src/main/java/com/example/restservice/GreetingController.java

package com.example.restservice;

import java.util.concurrent.atomic.AtomicLong;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

	private static final String template = "Hello, %s!";
	private final AtomicLong counter = new AtomicLong();

	@GetMapping("/greeting")
	public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
		return new Greeting(counter.incrementAndGet(), String.format(template, name));
	}
}

4. run

./gradlew bootRun

alternatively, you can create jar and run.

./gradlew build
java -jar ./build/libs/rest-service-0.0.1-SNAPSHOT.jar

5. test

http://localhost:8080/greeting

{"id":1,"content":"Hello, World!"}

http://localhost:8080/greeting?name=User

{"id":2,"content":"Hello, User!"}

Thoughts

So easy and simple!

The great things about using this are:

  • you do not need JSON conversion manually and
  • “there is no web.xml file, either. This web application is 100% pure Java”

as mentioned in the original guide.


Comments

Popular posts from this blog

Minikube Installation for M1 Mac

Selenide: Quick Start

PyCharm: Quick Start