Spring > REST


Create a web service

// ...
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
public class GreetingController {
	private static final String template = "Hello, %s!";
	private final AtomicLong counter = new AtomicLong();
	@RequestMapping(method=RequestMethod.GET, value="/greeting")
	public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
		return new Greeting(counter.incrementAndGet(), String.format(template, name));
  • Spring Boot automatically finds this controller ! We don't have to mention it in Application.java
  • “This code uses Spring 4’s new @RestController annotation, which marks the class as a controller where every method returns a domain object instead of a view. It’s shorthand for @Controller and @ResponseBody rolled together.”
  • “The @RequestMapping annotation ensures that HTTP requests to /greeting are mapped to the greeting() method.”
  • Greeting is a POJO with fields “id” (long) and “content” (String).

Comsume (=contact) a web service

// ...
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.client.RestTemplate;
public class Application implements CommandLineRunner {
    private static final Logger log = LoggerFactory.getLogger(Application.class);
    public static void main(String args[]) {
    public void run(String... args) throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
  • Quote is a POJO with fields “type” (String) and “value” (Value)
  • Value is a POJO with fields “id” (Long) and “quote” (String)

Annotation @JsonIgnoreProperties

@JsonIgnoreProperties(ignoreUnknown = true)

Applied to a POJO, this annotation makes sure that if we receive unexpected extra properties, they're ignored.