Spring > REST

Guides

Create a web service

GreetingController.java
// ...
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;
 
@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

Application.java
// ...
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.client.RestTemplate;
 
@SpringBootApplication
public class Application implements CommandLineRunner {
 
    private static final Logger log = LoggerFactory.getLogger(Application.class);
 
    public static void main(String args[]) {
        SpringApplication.run(Application.class);
    }
 
    @Override
    public void run(String... args) throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
        log.info(quote.toString());
    }
}
  • 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.

Print/export