Service Registration with Eureka ”; Previous Next In this chapter, you are going to learn in detail about How to register the Spring Boot Micro service application into the Eureka Server. Before registering the application, please make sure Eureka Server is running on the port 8761 or first build the Eureka Server and run it. For further information on building the Eureka server, you can refer to the previous chapter. First, you need to add the following dependencies in our build configuration file to register the microservice with the Eureka server. Maven users can add the following dependencies into the pom.xml file − <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> Gradle users can add the following dependencies into the build.gradle file − compile(”org.springframework.cloud:spring-cloud-starter-eureka”) Now, we need to add the @EnableEurekaClient annotation in the main Spring Boot application class file. The @EnableEurekaClient annotation makes your Spring Boot application act as a Eureka client. The main Spring Boot application is as given below − package com.tutorialspoint.eurekaclient; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @SpringBootApplication @EnableEurekaClient public class EurekaclientApplication { public static void main(String[] args) { SpringApplication.run(EurekaclientApplication.class, args); } } To register the Spring Boot application into Eureka Server we need to add the following configuration in our application.properties file or application.yml file and specify the Eureka Server URL in our configuration. The code for application.yml file is given below − eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka instance: preferIpAddress: true spring: application: name: eurekaclient The code for application.properties file is given below − eureka.client.serviceUrl.defaultZone = http://localhost:8761/eureka eureka.client.instance.preferIpAddress = true spring.application.name = eurekaclient Now, add the Rest Endpoint to return String in the main Spring Boot application and the Spring Boot Starter web dependency in build configuration file. Observe the code given below − package com.tutorialspoint.eurekaclient; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @EnableEurekaClient @RestController public class EurekaclientApplication { public static void main(String[] args) { SpringApplication.run(EurekaclientApplication.class, args); } @RequestMapping(value = “/”) public String home() { return “Eureka Client application”; } } The entire configuration file is given below. For Maven user – 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.tutorialspoint</groupId> <artifactId>eurekaclient</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>eurekaclient</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!– lookup parent from repository –> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <spring-cloud.version>Edgware.RELEASE</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <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> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </projecta> For Gradle user – build.gradle buildscript { ext { springBootVersion = ”1.5.9.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } ext { springCloudVersion = ”Edgware.RELEASE” } dependencies { compile(”org.springframework.cloud:spring-cloud-starter-eureka”) testCompile(”org.springframework.boot:spring-boot-starter-test”) compile(”org.springframework.boot:spring-boot-starter-web”) } dependencyManagement { imports { mavenBom “org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}” } } You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands − For Maven, you can use the following command − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the following command − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Now, run the JAR file by using the command as shown − java –jar <JARFILE> Now, the application has started on the Tomcat port 8080 and Eureka Client application is registered with the Eureka Server as shown below − Hit the URL http://localhost:8761/ in your web browser and you can see the Eureka Client application is registered with Eureka Server. Now hit the URL http://localhost:8080/ in your web browser and see the Rest Endpoint output. Print Page Previous Next Advertisements ”;
Category: spring Boot
Spring Boot – Runners
Spring Boot – Runners ”; Previous Next Application Runner and Command Line Runner interfaces lets you to execute the code after the Spring Boot application is started. You can use these interfaces to perform any actions immediately after the application has started. This chapter talks about them in detail. Application Runner Application Runner is an interface used to execute the code after the Spring Boot application started. The example given below shows how to implement the Application Runner interface on the main class file. package com.tutorialspoint.demo; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication implements ApplicationRunner { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Override public void run(ApplicationArguments arg0) throws Exception { System.out.println(“Hello World from Application Runner”); } } Now, if you observe the console window below Hello World from Application Runner, the println statement is executed after the Tomcat started. Is the following screenshot relevant? Command Line Runner Command Line Runner is an interface. It is used to execute the code after the Spring Boot application started. The example given below shows how to implement the Command Line Runner interface on the main class file. package com.tutorialspoint.demo; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Override public void run(String… arg0) throws Exception { System.out.println(“Hello world from Command Line Runner”); } } Look at the console window below “Hello world from Command Line Runner” println statement is executed after the Tomcat started. Print Page Previous Next Advertisements ”;
Spring Boot – Exception Handling ”; Previous Next Handling exceptions and errors in APIs and sending the proper response to the client is good for enterprise applications. In this chapter, we will learn how to handle exceptions in Spring Boot. Before proceeding with exception handling, let us gain an understanding on the following annotations. Controller Advice The @ControllerAdvice is an annotation, to handle the exceptions globally. Exception Handler The @ExceptionHandler is an annotation used to handle the specific exceptions and sending the custom responses to the client. You can use the following code to create @ControllerAdvice class to handle the exceptions globally − package com.tutorialspoint.demo.exception; import org.springframework.web.bind.annotation.ControllerAdvice; @ControllerAdvice public class ProductExceptionController { } Define a class that extends the RuntimeException class. package com.tutorialspoint.demo.exception; public class ProductNotfoundException extends RuntimeException { private static final long serialVersionUID = 1L; } You can define the @ExceptionHandler method to handle the exceptions as shown. This method should be used for writing the Controller Advice class file. @ExceptionHandler(value = ProductNotfoundException.class) public ResponseEntity<Object> exception(ProductNotfoundException exception) { } Now, use the code given below to throw the exception from the API. @RequestMapping(value = “/products/{id}”, method = RequestMethod.PUT) public ResponseEntity<Object> updateProduct() { throw new ProductNotfoundException(); } The complete code to handle the exception is given below. In this example, we used the PUT API to update the product. Here, while updating the product, if the product is not found, then return the response error message as “Product not found”. Note that the ProductNotFoundException exception class should extend the RuntimeException. package com.tutorialspoint.demo.exception; public class ProductNotfoundException extends RuntimeException { private static final long serialVersionUID = 1L; } The Controller Advice class to handle the exception globally is given below. We can define any Exception Handler methods in this class file. package com.tutorialspoint.demo.exception; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class ProductExceptionController { @ExceptionHandler(value = ProductNotfoundException.class) public ResponseEntity<Object> exception(ProductNotfoundException exception) { return new ResponseEntity<>(“Product not found”, HttpStatus.NOT_FOUND); } } The Product Service API controller file is given below to update the Product. If the Product is not found, then it throws the ProductNotFoundException class. package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.exception.ProductNotfoundException; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); static { Product honey = new Product(); honey.setId(“1”); honey.setName(“Honey”); productRepo.put(honey.getId(), honey); Product almond = new Product(); almond.setId(“2”); almond.setName(“Almond”); productRepo.put(almond.getId(), almond); } @RequestMapping(value = “/products/{id}”, method = RequestMethod.PUT) public ResponseEntity<Object> updateProduct(@PathVariable(“id”) String id, @RequestBody Product product) { if(!productRepo.containsKey(id))throw new ProductNotfoundException(); productRepo.remove(id); product.setId(id); productRepo.put(id, product); return new ResponseEntity<>(“Product is updated successfully”, HttpStatus.OK); } } The code for main Spring Boot application class file is given below − package com.tutorialspoint.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } The code for POJO class for Product is given below − package com.tutorialspoint.demo.model; public class Product { private String id; private String name; 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; } } The code for Maven build – pom.xml is shown below − <?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.tutorialspoint</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <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> The code for Gradle Build – build.gradle is given below − buildscript { ext { springBootVersion = ”1.5.8.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands − For Maven, you can use the following command − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the following command − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. You can run the JAR file by using the following command − java –jar <JARFILE> This will start the application on the Tomcat port 8080 as shown below − Now hit the below URL in POSTMAN application and you can see the output as shown below − Update URL: http://localhost:8080/products/3 Print Page Previous Next Advertisements ”;
Spring Boot – Servlet Filter
Spring Boot – Servlet Filter ”; Previous Next A filter is an object used to intercept the HTTP requests and responses of your application. By using filter, we can perform two operations at two instances − Before sending the request to the controller Before sending a response to the client. The following code shows the sample code for a Servlet Filter implementation class with @Component annotation. @Component public class SimpleFilter implements Filter { @Override public void destroy() {} @Override public void doFilter (ServletRequest request, ServletResponse response, FilterChain filterchain) throws IOException, ServletException {} @Override public void init(FilterConfig filterconfig) throws ServletException {} } The following example shows the code for reading the remote host and remote address from the ServletRequest object before sending the request to the controller. In doFilter() method, we have added the System.out.println statements to print the remote host and remote address. package com.tutorialspoint.demo; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.springframework.stereotype.Component; @Component public class SimpleFilter implements Filter { @Override public void destroy() {} @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterchain) throws IOException, ServletException { System.out.println(“Remote Host:”+request.getRemoteHost()); System.out.println(“Remote Address:”+request.getRemoteAddr()); filterchain.doFilter(request, response); } @Override public void init(FilterConfig filterconfig) throws ServletException {} } In the Spring Boot main application class file, we have added the simple REST endpoint that returns the “Hello World” string. package com.tutorialspoint.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @RequestMapping(value = “/”) public String hello() { return “Hello World”; } } The code for Maven build – pom.xml is given below − <?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.tutorialspoint</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <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> The code for Gradle Build – build.gradle is given below − buildscript { ext { springBootVersion = ”1.5.8.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands shown below − For Maven, use the command as shown below − mvn clean install After BUILD SUCCESS, you can find the JAR file under the target directory. For Gradle, use the command as shown below − gradle clean build After BUILD SUCCESSFUL, you can find the JAR file under the build/libs directory. Now, run the JAR file by using the following command java –jar <JARFILE> You can see the application has started on the Tomcat port 8080. Now hit the URL http://localhost:8080/ and see the output Hello World. It should look as shown below − Then, you can see the Remote host and Remote address on the console log as shown below − Print Page Previous Next Advertisements ”;
Spring Boot – Rest Template
Spring Boot – Rest Template ”; Previous Next Rest Template is used to create applications that consume RESTful Web Services. You can use the exchange() method to consume the web services for all HTTP methods. The code given below shows how to create Bean for Rest Template to auto wiring the Rest Template object. package com.tutorialspoint.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean public RestTemplate getRestTemplate() { return new RestTemplate(); } } GET Consuming the GET API by using RestTemplate – exchange() method Assume this URL http://localhost:8080/products returns the following JSON and we are going to consume this API response by using Rest Template using the following code − [ { “id”: “1”, “name”: “Honey” }, { “id”: “2”, “name”: “Almond” } ] You will have to follow the given points to consume the API − Autowired the Rest Template Object. Use HttpHeaders to set the Request Headers. Use HttpEntity to wrap the request object. Provide the URL, HttpMethod, and Return type for Exchange() method. @RestController public class ConsumeWebService { @Autowired RestTemplate restTemplate; @RequestMapping(value = “/template/products”) public String getProductList() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity <String> entity = new HttpEntity<String>(headers); return restTemplate.exchange(” http://localhost:8080/products”, HttpMethod.GET, entity, String.class).getBody(); } } POST Consuming POST API by using RestTemplate – exchange() method Assume this URL http://localhost:8080/products returns the response shown below, we are going to consume this API response by using the Rest Template. The code given below is the Request body − { “id”:”3″, “name”:”Ginger” } The code given below is the Response body − Product is created successfully You will have to follow the points given below to consume the API − Autowired the Rest Template Object. Use the HttpHeaders to set the Request Headers. Use the HttpEntity to wrap the request object. Here, we wrap the Product object to send it to the request body. Provide the URL, HttpMethod, and Return type for exchange() method. @RestController public class ConsumeWebService { @Autowired RestTemplate restTemplate; @RequestMapping(value = “/template/products”, method = RequestMethod.POST) public String createProducts(@RequestBody Product product) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<Product> entity = new HttpEntity<Product>(product,headers); return restTemplate.exchange( “http://localhost:8080/products”, HttpMethod.POST, entity, String.class).getBody(); } } PUT Consuming PUT API by using RestTemplate – exchange() method Assume this URL http://localhost:8080/products/3 returns the below response and we are going to consume this API response by using Rest Template. The code given below is Request body − { “name”:”Indian Ginger” } The code given below is the Response body − Product is updated successfully You will have to follow the points given below to consume the API − Autowired the Rest Template Object. Use HttpHeaders to set the Request Headers. Use HttpEntity to wrap the request object. Here, we wrap the Product object to send it to the request body. Provide the URL, HttpMethod, and Return type for exchange() method. @RestController public class ConsumeWebService { @Autowired RestTemplate restTemplate; @RequestMapping(value = “/template/products/{id}”, method = RequestMethod.PUT) public String updateProduct(@PathVariable(“id”) String id, @RequestBody Product product) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<Product> entity = new HttpEntity<Product>(product,headers); return restTemplate.exchange( “http://localhost:8080/products/”+id, HttpMethod.PUT, entity, String.class).getBody(); } } DELETE Consuming DELETE API by using RestTemplate – exchange() method Assume this URL http://localhost:8080/products/3 returns the response given below and we are going to consume this API response by using Rest Template. This line of code shown below is the Response body − Product is deleted successfully You will have to follow the points shown below to consume the API − Autowired the Rest Template Object. Use HttpHeaders to set the Request Headers. Use HttpEntity to wrap the request object. Provide the URL, HttpMethod, and Return type for exchange() method. @RestController public class ConsumeWebService { @Autowired RestTemplate restTemplate; @RequestMapping(value = “/template/products/{id}”, method = RequestMethod.DELETE) public String deleteProduct(@PathVariable(“id”) String id) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<Product> entity = new HttpEntity<Product>(headers); return restTemplate.exchange( “http://localhost:8080/products/”+id, HttpMethod.DELETE, entity, String.class).getBody(); } } The complete Rest Template Controller class file is given below − package com.tutorialspoint.demo.controller; import java.util.Arrays; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import com.tutorialspoint.demo.model.Product; @RestController public class ConsumeWebService { @Autowired RestTemplate restTemplate; @RequestMapping(value = “/template/products”) public String getProductList() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<String> entity = new HttpEntity<String>(headers); return restTemplate.exchange( “http://localhost:8080/products”, HttpMethod.GET, entity, String.class).getBody(); } @RequestMapping(value = “/template/products”, method = RequestMethod.POST) public String createProducts(@RequestBody Product product) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<Product> entity = new HttpEntity<Product>(product,headers); return restTemplate.exchange( “http://localhost:8080/products”, HttpMethod.POST, entity, String.class).getBody(); } @RequestMapping(value = “/template/products/{id}”, method = RequestMethod.PUT) public String updateProduct(@PathVariable(“id”) String id, @RequestBody Product product) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<Product> entity = new HttpEntity<Product>(product,headers); return restTemplate.exchange( “http://localhost:8080/products/”+id, HttpMethod.PUT, entity, String.class).getBody(); } @RequestMapping(value = “/template/products/{id}”, method = RequestMethod.DELETE) public String deleteProduct(@PathVariable(“id”) String id) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<Product> entity = new HttpEntity<Product>(headers); return restTemplate.exchange( “http://localhost:8080/products/”+id, HttpMethod.DELETE, entity, String.class).getBody(); } } The code for Spring Boot Application Class – DemoApplication.java is given below − package com.tutorialspoint.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } The code for Maven build – pom.xml is given below − <?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.tutorialspoint</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <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> The code for Gradle Build – build.gradle is given below − buildscript { ext { springBootVersion = ”1.5.8.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } You can create an executable JAR file, and run the Spring Boot application by using the
Spring Boot – Building RESTful Web Services ”; Previous Next Spring Boot provides a very good support to building RESTful Web Services for enterprise applications. This chapter will explain in detail about building RESTful web services using Spring Boot. Note − For building a RESTful Web Services, we need to add the Spring Boot Starter Web dependency into the build configuration file. If you are a Maven user, use the following code to add the below dependency in your pom.xml file − <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> If you are a Gradle user, use the following code to add the below dependency in your build.gradle file. compile(”org.springframework.boot:spring-boot-starter-web”) The code for complete build configuration file Maven build – pom.xml is given below − <?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.tutorialspoint</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <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> The code for complete build configuration file Gradle Build – build.gradle is given below − buildscript { ext { springBootVersion = ”1.5.8.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } Before you proceed to build a RESTful web service, it is suggested that you have knowledge of the following annotations − Rest Controller The @RestController annotation is used to define the RESTful web services. It serves JSON, XML and custom response. Its syntax is shown below − @RestController public class ProductServiceController { } Request Mapping The @RequestMapping annotation is used to define the Request URI to access the REST Endpoints. We can define Request method to consume and produce object. The default request method is GET. @RequestMapping(value = “/products”) public ResponseEntity<Object> getProducts() { } Request Body The @RequestBody annotation is used to define the request body content type. public ResponseEntity<Object> createProduct(@RequestBody Product product) { } Path Variable The @PathVariable annotation is used to define the custom or dynamic request URI. The Path variable in request URI is defined as curly braces {} as shown below − public ResponseEntity<Object> updateProduct(@PathVariable(“id”) String id) { } Request Parameter The @RequestParam annotation is used to read the request parameters from the Request URL. By default, it is a required parameter. We can also set default value for request parameters as shown here − public ResponseEntity<Object> getProduct( @RequestParam(value = “name”, required = false, defaultValue = “honey”) String name) { } GET API The default HTTP request method is GET. This method does not require any Request Body. You can send request parameters and path variables to define the custom or dynamic URL. The sample code to define the HTTP GET request method is shown below. In this example, we used HashMap to store the Product. Note that we used a POJO class as the product to be stored. Here, the request URI is /products and it will return the list of products from HashMap repository. The controller class file is given below that contains GET method REST Endpoint. package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); static { Product honey = new Product(); honey.setId(“1”); honey.setName(“Honey”); productRepo.put(honey.getId(), honey); Product almond = new Product(); almond.setId(“2”); almond.setName(“Almond”); productRepo.put(almond.getId(), almond); } @RequestMapping(value = “/products”) public ResponseEntity<Object> getProduct() { return new ResponseEntity<>(productRepo.values(), HttpStatus.OK); } } POST API The HTTP POST request is used to create a resource. This method contains the Request Body. We can send request parameters and path variables to define the custom or dynamic URL. The following example shows the sample code to define the HTTP POST request method. In this example, we used HashMap to store the Product, where the product is a POJO class. Here, the request URI is /products, and it will return the String after storing the product into HashMap repository. package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); @RequestMapping(value = “/products”, method = RequestMethod.POST) public ResponseEntity<Object> createProduct(@RequestBody Product product) { productRepo.put(product.getId(), product); return new ResponseEntity<>(“Product is created successfully”, HttpStatus.CREATED); } } PUT API The HTTP PUT request is used to update the existing resource. This method contains a Request Body. We can send request parameters and path variables to define the custom or dynamic URL. The example given below shows how to define the HTTP PUT request method. In this example, we used HashMap to update the existing Product, where the product is a POJO class. Here the request URI is /products/{id} which will return the String after a the product into a HashMap repository. Note that we used the Path variable {id} which defines the products ID that needs to be updated. package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); @RequestMapping(value = “/products/{id}”, method = RequestMethod.PUT) public ResponseEntity<Object> updateProduct(@PathVariable(“id”) String id, @RequestBody Product product) { productRepo.remove(id); product.setId(id); productRepo.put(id, product); return new ResponseEntity<>(“Product is updated successsfully”, HttpStatus.OK); } } DELETE API The HTTP Delete request is used to delete the existing resource. This method does not contain any Request Body. We can send request parameters and path variables to define the custom or dynamic URL. The example given below shows how to define the HTTP DELETE request method. In this example, we used HashMap to remove the existing product, which is a POJO class. The request URI is /products/{id} and it will return the String after deleting the product from HashMap repository. We used the
Spring Boot – Google Cloud Platform ”; Previous Next Google Cloud Platform provides a cloud computing services that run the Spring Boot application in the cloud environment. In this chapter, we are going to see how to deploy the Spring Boot application in GCP app engine platform. First, download the Gradle build Spring Boot application from Spring Initializer page www.start.spring.io. Observe the following screenshot. Now, in build.gradle file, add the Google Cloud appengine plugin and appengine classpath dependency. The code for build.gradle file is given below − buildscript { ext { springBootVersion = ”1.5.9.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) classpath ”com.google.cloud.tools:appengine-gradle-plugin:1.3.3” } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” apply plugin: ”com.google.cloud.tools.appengine” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } Now, write a simple HTTP Endpoint and it returns the String success as shown − package com.tutorialspoint.appenginedemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class AppengineDemoApplication { public static void main(String[] args) { SpringApplication.run(AppengineDemoApplication.class, args); } @RequestMapping(value = “/”) public String success() { return “APP Engine deployment success”; } } Next, add the app.yml file under src/main/appengine directory as shown − runtime: java env: flex handlers: – url: /.* script: this field is required, but ignored Now, go to the Google Cloud console and click the Activate Google cloud shell at the top of the page. Now, move your source files and Gradle file into home directory of your google cloud machine by using google cloud shell. Now, execute the command gradle appengineDeploy and it will deploy your application into the Google Cloud appengine. Note − GCP should be billing enabled and before deploying your application into appengine, you should create appengine platform in GCP. It will take few minutes to deploy your application into GCP appengine platform. After build successful you can see the Service URL in console window. Now, hit the service URL and see the output. Google Cloud SQL To connect the Google Cloud SQL into your Spring Boot application, you should add the following properties into your application.properties file. JDBC URL Format jdbc:mysql://google/<DATABASE-NAME>?cloudSqlInstance = <GOOGLE_CLOUD_SQL_INSTANCE_NAME> &socketFactory = com.google.cloud.sql.mysql.SocketFactory&user = <USERNAME>&password = <PASSWORD> Note − The Spring Boot application and Google Cloud SQL should be in same GCP project. The application.properties file is given below. spring.dbProductService.driverClassName = com.mysql.jdbc.Driver spring.dbProductService.url = jdbc:mysql://google/PRODUCTSERVICE?cloudSqlInstance = springboot-gcp-cloudsql:asia-northeast1:springboot-gcp-cloudsql-instance&socketFactory = com.google.cloud.sql.mysql.SocketFactory&user = root&password = rootspring.dbProductService.username = root spring.dbProductService.password = root spring.dbProductService.testOnBorrow = true spring.dbProductService.testWhileIdle = true spring.dbProductService.timeBetweenEvictionRunsMillis = 60000 spring.dbProductService.minEvictableIdleTimeMillis = 30000 spring.dbProductService.validationQuery = SELECT 1 spring.dbProductService.max-active = 15 spring.dbProductService.max-idle = 10 spring.dbProductService.max-wait = 8000 YAML file users can add the below properties to your application.yml file. spring: datasource: driverClassName: com.mysql.jdbc.Driver url: “jdbc:mysql://google/PRODUCTSERVICE?cloudSqlInstance=springboot-gcp-cloudsql:asia-northeast1:springboot-gcp-cloudsql-instance&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=root&password=root” password: “root” username: “root” testOnBorrow: true testWhileIdle: true validationQuery: SELECT 1 max-active: 15 max-idle: 10 max-wait: 8000 Print Page Previous Next Advertisements ”;
Spring Boot – Batch Service
Spring Boot – Batch Service ”; Previous Next You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands as shown below − For Maven, you can use the command given below − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the command as shown − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Run the JAR file by using the command given here − java –jar <JARFILE> Now, the application has started on the Tomcat port 8080 as shown. Now, hit the URL http://localhost:8080/ in your web browser and connect the web socket and send the greeting and receive the message. Batch Service is a process to execute more than one command in a single task. In this chapter, you are going to learn how to create batch service in a Spring Boot application. Let us consider an example where we are going to save the CSV file content into HSQLDB. To create a Batch Service program, we need to add the Spring Boot Starter Batch dependency and HSQLDB dependency in our build configuration file. Maven users can add the following dependencies in pom.xml file. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-batch</artifactId> </dependency> <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> </dependency> Gradle users can add the following dependencies in build.gradle file. compile(“org.springframework.boot:spring-boot-starter-batch”) compile(“org.hsqldb:hsqldb”) Now, add the simple CSV data file under classpath resources – src/main/resources and name the file as file.csv as shown − William,John Mike, Sebastian Lawarance, Lime Next, write a SQL script for HSQLDB – under the classpath resource directory – request_fail_hystrix_timeout DROP TABLE USERS IF EXISTS; CREATE TABLE USERS ( user_id BIGINT IDENTITY NOT NULL PRIMARY KEY, first_name VARCHAR(20), last_name VARCHAR(20) ); Create a POJO class for USERS model as shown − package com.tutorialspoint.batchservicedemo; public class User { private String lastName; private String firstName; public User() { } public User(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public String toString() { return “firstName: ” + firstName + “, lastName: ” + lastName; } } Now, create an intermediate processor to do the operations after the reading the data from the CSV file and before writing the data into SQL. package com.tutorialspoint.batchservicedemo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.item.ItemProcessor; public class UserItemProcessor implements ItemProcessor<User, User> { private static final Logger log = LoggerFactory.getLogger(UserItemProcessor.class); @Override public User process(final User user) throws Exception { final String firstName = user.getFirstName().toUpperCase(); final String lastName = user.getLastName().toUpperCase(); final User transformedPerson = new User(firstName, lastName); log.info(“Converting (” + user + “) into (” + transformedPerson + “)”); return transformedPerson; } } Let us create a Batch configuration file, to read the data from CSV and write into the SQL file as shown below. We need to add the @EnableBatchProcessing annotation in the configuration class file. The @EnableBatchProcessing annotation is used to enable the batch operations for your Spring Boot application. package com.tutorialspoint.batchservicedemo; import javax.sql.DataSource; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.core.launch.support.RunIdIncrementer; import org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider; import org.springframework.batch.item.database.JdbcBatchItemWriter; import org.springframework.batch.item.file.FlatFileItemReader; import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper; import org.springframework.batch.item.file.mapping.DefaultLineMapper; import org.springframework.batch.item.file.transform.DelimitedLineTokenizer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; @Configuration @EnableBatchProcessing public class BatchConfiguration { @Autowired public JobBuilderFactory jobBuilderFactory; @Autowired public StepBuilderFactory stepBuilderFactory; @Autowired public DataSource dataSource; @Bean public FlatFileItemReader<User> reader() { FlatFileItemReader<User> reader = new FlatFileItemReader<User>(); reader.setResource(new ClassPathResource(“file.csv”)); reader.setLineMapper(new DefaultLineMapper<User>() { { setLineTokenizer(new DelimitedLineTokenizer() { { setNames(new String[] { “firstName”, “lastName” }); } }); setFieldSetMapper(new BeanWrapperFieldSetMapper<User>() { { setTargetType(User.class); } }); } }); return reader; } @Bean public UserItemProcessor processor() { return new UserItemProcessor(); } @Bean public JdbcBatchItemWriter<User> writer() { JdbcBatchItemWriter<User> writer = new JdbcBatchItemWriter<User>(); writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<User>()); writer.setSql(“INSERT INTO USERS (first_name, last_name) VALUES (:firstName, :lastName)”); writer.setDataSource(dataSource); return writer; } @Bean public Job importUserJob(JobCompletionNotificationListener listener) { return jobBuilderFactory.get(“importUserJob”).incrementer( new RunIdIncrementer()).listener(listener).flow(step1()).end().build(); } @Bean public Step step1() { return stepBuilderFactory.get(“step1”).<User, User>chunk(10).reader(reader()).processor(processor()).writer(writer()).build(); } } The reader() method is used to read the data from the CSV file and writer() method is used to write a data into the SQL. Next, we will have to write a Job Completion Notification Listener class – used to notify after the Job completion. package com.tutorialspoint.batchservicedemo; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.listener.JobExecutionListenerSupport; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Component; @Component public class JobCompletionNotificationListener extends JobExecutionListenerSupport { private static final Logger log = LoggerFactory.getLogger(JobCompletionNotificationListener.class); private final JdbcTemplate jdbcTemplate; @Autowired public JobCompletionNotificationListener(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public void afterJob(JobExecution jobExecution) { if (jobExecution.getStatus() == BatchStatus.COMPLETED) { log.info(“!!! JOB FINISHED !! It”s time to verify the results!!”); List<User> results = jdbcTemplate.query( “SELECT first_name, last_name FROM USERS”, new RowMapper<User>() { @Override public User mapRow(ResultSet rs, int row) throws SQLException { return new User(rs.getString(1), rs.getString(2)); } }); for (User person : results) { log.info(“Found <” + person + “> in the database.”); } } } } Now, create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands. For Maven, use the command as shown − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the command as shown − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Run the JAR file by using the command given here − java –jar <JARFILE> You can see the output in console window as shown − Print Page Previous Next Advertisements ”;
Spring Boot – Unit Test Cases ”; Previous Next Unit Testing is a one of the testing done by the developers to make sure individual unit or component functionalities are working fine. In this tutorial, we are going to see how to write a unit test case by using Mockito and Web Controller. Mockito For injecting Mockito Mocks into Spring Beans, we need to add the Mockito-core dependency in our build configuration file. Maven users can add the following dependency in your pom.xml file. <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>2.13.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> Gradle users can add the following dependency in the build.gradle file. compile group: ”org.mockito”, name: ”mockito-core”, version: ”2.13.0” testCompile(”org.springframework.boot:spring-boot-starter-test”) The code to write a Service class which contains a method that returns the String value is given here. package com.tutorialspoint.mockitodemo; import org.springframework.stereotype.Service; @Service public class ProductService { public String getProductName() { return “Honey”; } } Now, inject the ProductService class into another Service class file as shown. package com.tutorialspoint.mockitodemo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class OrderService { @Autowired ProductService productService; public OrderService(ProductService productService) { this.productService = productService; } public String getProductName() { return productService.getProductName(); } } The main Spring Boot application class file is given below − package com.tutorialspoint.mockitodemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MockitoDemoApplication { public static void main(String[] args) { SpringApplication.run(MockitoDemoApplication.class, args); } } Then, configure the Application context for the tests. The @Profile(“test”) annotation is used to configure the class when the Test cases are running. package com.tutorialspoint.mockitodemo; import org.mockito.Mockito; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Profile; @Profile(“test”) @Configuration public class ProductServiceTestConfiguration { @Bean @Primary public ProductService productService() { return Mockito.mock(ProductService.class); } } Now, you can write a Unit Test case for Order Service under the src/test/resources package. package com.tutorialspoint.mockitodemo; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @SpringBootTest @ActiveProfiles(“test”) @RunWith(SpringJUnit4ClassRunner.class) public class MockitoDemoApplicationTests { @Autowired private OrderService orderService; @Autowired private ProductService productService; @Test public void whenUserIdIsProvided_thenRetrievedNameIsCorrect() { Mockito.when(productService.getProductName()).thenReturn(“Mock Product Name”); String testName = orderService.getProductName(); Assert.assertEquals(“Mock Product Name”, testName); } } The complete code for build configuration file is given below. Maven – 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.tutorialspoint</groupId> <artifactId>mockito-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>mockito-demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath /> <!– lookup parent from repository –> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>2.13.0</version> </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> Gradle – build.gradle buildscript { ext { springBootVersion = ”1.5.9.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter”) compile group: ”org.mockito”, name: ”mockito-core”, version: ”2.13.0” testCompile(”org.springframework.boot:spring-boot-starter-test”) } You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle1 commands. For Maven, you can use the command as shown − mvn clean install You can see the test results in console window. For Gradle, you can use the command as shown − gradle clean build You can see the rest results in console window. Print Page Previous Next Advertisements ”;
Rest Controller Unit Test
Spring Boot – Rest Controller Unit Test ”; Previous Next Spring Boot provides an easy way to write a Unit Test for Rest Controller file. With the help of SpringJUnit4ClassRunner and MockMvc, we can create a web application context to write Unit Test for Rest Controller file. Unit Tests should be written under the src/test/java directory and classpath resources for writing a test should be placed under the src/test/resources directory. For Writing a Unit Test, we need to add the Spring Boot Starter Test dependency in your build configuration file as shown below. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> Gradle users can add the following dependency in your build.gradle file. testCompile(”org.springframework.boot:spring-boot-starter-test”) Before writing a Test case, we should first build RESTful web services. For further information on building RESTful web services, please refer to the chapter on the same given in this tutorial. Writing a Unit Test for REST Controller In this section, let us see how to write a Unit Test for the REST Controller. First, we need to create Abstract class file used to create web application context by using MockMvc and define the mapToJson() and mapFromJson() methods to convert the Java object into JSON string and convert the JSON string into Java object. package com.tutorialspoint.demo; import java.io.IOException; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = DemoApplication.class) @WebAppConfiguration public abstract class AbstractTest { protected MockMvc mvc; @Autowired WebApplicationContext webApplicationContext; protected void setUp() { mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } protected String mapToJson(Object obj) throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.writeValueAsString(obj); } protected <T> T mapFromJson(String json, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readValue(json, clazz); } } Next, write a class file that extends the AbstractTest class and write a Unit Test for each method such GET, POST, PUT and DELETE. The code for GET API Test case is given below. This API is to view the list of products. @Test public void getProductsList() throws Exception { String uri = “/products”; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri) .accept(MediaType.APPLICATION_JSON_VALUE)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); Product[] productlist = super.mapFromJson(content, Product[].class); assertTrue(productlist.length > 0); } The code for POST API test case is given below. This API is to create a product. @Test public void createProduct() throws Exception { String uri = “/products”; Product product = new Product(); product.setId(“3”); product.setName(“Ginger”); String inputJson = super.mapToJson(product); MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri) .contentType(MediaType.APPLICATION_JSON_VALUE).content(inputJson)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(201, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, “Product is created successfully”); } The code for PUT API Test case is given below. This API is to update the existing product. @Test public void updateProduct() throws Exception { String uri = “/products/2”; Product product = new Product(); product.setName(“Lemon”); String inputJson = super.mapToJson(product); MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.put(uri) .contentType(MediaType.APPLICATION_JSON_VALUE).content(inputJson)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, “Product is updated successsfully”); } The code for Delete API Test case is given below. This API will delete the existing product. @Test public void deleteProduct() throws Exception { String uri = “/products/2”; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.delete(uri)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, “Product is deleted successsfully”); } The full Controller Test class file is given below − package com.tutorialspoint.demo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import com.tutorialspoint.demo.model.Product; public class ProductServiceControllerTest extends AbstractTest { @Override @Before public void setUp() { super.setUp(); } @Test public void getProductsList() throws Exception { String uri = “/products”; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri) .accept(MediaType.APPLICATION_JSON_VALUE)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); Product[] productlist = super.mapFromJson(content, Product[].class); assertTrue(productlist.length > 0); } @Test public void createProduct() throws Exception { String uri = “/products”; Product product = new Product(); product.setId(“3”); product.setName(“Ginger”); String inputJson = super.mapToJson(product); MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(inputJson)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(201, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, “Product is created successfully”); } @Test public void updateProduct() throws Exception { String uri = “/products/2”; Product product = new Product(); product.setName(“Lemon”); String inputJson = super.mapToJson(product); MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.put(uri) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(inputJson)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, “Product is updated successsfully”); } @Test public void deleteProduct() throws Exception { String uri = “/products/2”; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.delete(uri)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, “Product is deleted successsfully”); } } You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands given below − For Maven, you can use the command given below − mvn clean install Now, you can see the test results in console window. For Gradle, you can use the command as shown below − gradle clean build You can see the rest results in console window as shown below. Print Page Previous Next Advertisements ”;