In this article we will build a REST application using Spring Boot. Spring Boot aims at simplifying Spring application bootstrapping by providing a set of starter project templates. The project templates help add the necessary dependencies. In case of a REST application, we need to add spring-boot-starter-web
which in turn will add spring-boot-starter
, spring-boot-tomcat
, spring-web
, spring-webmvc
and few other artifacts. spring-boot-tomcat
enables creation of standalone Spring applications by embedding a Tomcat server
Build Spring REST project
We will first build a Spring Boot project using Spring Boot’s starter website http://start.spring.io. Enter the group and artifact information. Add web as the dependency and then click on ‘Generate Project’. Unzip the source code and import in Eclipse as a Maven project.
Dependencies
spring-boot-starter-parent
– This is the parent POM. It will provide the useful Maven defaults.spring-boot-starter-web
– Since we are developing a REST service, we will need spring web based dependencies. The web starter will also set up an embedded servlet container.spring-boot-starter-test
– This will addspring-test
module and test dependencies like JUnit, Hamcrest and Mockito.
spring-boot-starter
– The core Spring Boot starter, including auto-configuration support, logging and YAMLspring-boot-starter-tomcat
– provides an embedded servlet containerspring-boot-autoconfigure
– Spring Boot figures out how to configure based on the jar dependencies that you have added.spring-boot-starter-validation
– Adds hibernate validator, an implementation of bean validation APIjackson-databind
– JSON data bindingspring-web
andspring-webmvc
– spring web modules
pom.xml:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javarticle.spring.rest</groupId> <artifactId>SpringRESTExample</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>SpringRESTExample</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
In this example, we will create a REST service and a REST client.
REST Service
Our REST service will return all the employee objects.
Employee:
package com.javarticle.spring.rest; public class Employee { private String id; private String name; private int age; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
Let’s define few employees.
EmployeeSource:
package com.javarticle.spring.rest; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class EmployeeSource { private static final Map<String, Employee> EMPLOYEES = new HashMap<>(); static { Employee emp1 = new Employee(); emp1.setId("01"); emp1.setName("Joe"); emp1.setAge(32); Employee emp2 = new Employee(); emp2.setId("02"); emp2.setName("Sam"); emp2.setAge(41); Employee emp3 = new Employee(); emp3.setId("03"); emp3.setName("Phil"); emp3.setAge(22); EMPLOYEES.put(emp1.getId(), emp1); EMPLOYEES.put(emp2.getId(), emp2); EMPLOYEES.put(emp3.getId(), emp3); } public static Collection<Employee> getEmployees() { return EMPLOYEES.values(); } public static Employee getEmployee(String empId) { return EMPLOYEES.get(empId); } }
@RestController and @RequestMapping annotations
We now create a REST controller to handle the web request. Below are the annotations that we must be aware of:
@Controller
– Indicates that an annotated class is a “Controller”. Class annotated with@Controller
will be automatically registered as Spring Beans. It will look forRequestMapping
annotation for mapping web requests onto specific handler classes and/or handler methods.@ResponseBody
– If a@RequestMapping
method is annotated with@ResponseBody
, its return value will be bound to the web response body. If a method returns a POJO type object, spring will automatically convert it to a JSON style data format and append to the response.@RequestMapping
– It defines the routing information which spring will use to map a web request to a controller’s method@RestController
– A convenience annotation that combines@Controller
and@ResponseBody
Method getEmployeeNames
will be called as we enter http://localhost:8080/employees
in the browser.
RESTControllerExample:
package com.javarticle.spring.rest; import java.util.Collection; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class RESTControllerExample { @RequestMapping(value = "/employees", method = RequestMethod.GET) public Collection getEmployeeNames() { return EmployeeSource.getEmployees(); } }
REST Client
We now write a simple REST client to call the above REST service.
RESTClientExample:
package com.javarticle.spring.rest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; @Component("restClient") public class RESTClientExample { @Autowired private RestTemplate restTemplate; public String getAllEmployees() { return restTemplate.getForObject("http://localhost:8080/employees", String.class); } }
Spring Boot Main Application
The spring boot application will start the server and the make a REST call to our new service and retrieve the employees.
SpringRestExampleApplication:
package com.javarticle.spring.rest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication public class SpringRestExampleApplication { public static void main(String[] args) { ApplicationContext context = SpringApplication.run(SpringRestExampleApplication.class, args); System.out.println(( (RESTClientExample) context.getBean("restClient")).getAllEmployees()); } @Bean public RestTemplate geRestTemplate() { return new RestTemplate(); } }
Output:
[{"id":"01","name":"Joe","age":32},{"id":"02","name":"Sam","age":41},{"id":"03","name":"Phil","age":22}]
Download the source code
This was an example about Spring Boot REST services.