Spring Boot Tutorial
Spring Boot Tutorial
Spring Boot Tutorial
Advantages
Micro services offers the following advantages to its developers −
Easy deployment
Simple scalability
Compatible with Containers
Minimum configuration
Lesser production time
Spring Boot automatically scans all the components included in the project by
using @ComponentScan annotation.
Auto Configuration
Spring Boot Auto Configuration automatically configures your Spring application
based on the JAR dependencies you added in the project. For example, if MySQL
database is on your class path, but you have not configured any database
connection, then Spring Boot auto configures an in-memory database.
For this purpose, you need to add @EnableAutoConfiguration annotation
or @SpringBootApplication annotation to your main class file. Then, your Spring
Boot application will be automatically configured.
Observe the following code for a better understanding −
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@EnableAutoConfiguration
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Component Scan
Spring Boot application scans all the beans and package declarations when the
application initializes. You need to add the @ComponentScan annotation for your
class file to scan your components added in your project.
Spring Boot 4
@ComponentScan
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Spring Initializer
One of the ways to Bootstrapping a Spring Boot application is by using Spring
Initializer. To do this, you will have to visit the Spring Initializer web
page www.start.spring.io and choose your Build, Spring Boot Version and platform.
Also, you need to provide a Group, Artifact and required dependencies to run the
application.
Observe the following screenshot that shows an example where we added
the spring-boot-starter-web dependency to write REST Endpoints.
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);
}
}
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;
Spring Boot 5
import org.springframework.boot.builder.SpringApplicationBuilder;
import
org.springframework.boot.web.servlet.support.SpringBootServletIni
tializer;
@SpringBootApplication
public class DemoApplication extends
SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder
configure(SpringApplicationBuilder application) {
return application.sources(DemoApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Typical Layout
The typical layout of Spring Boot application is shown in the image given below −
package com.tutorialspoint.myproject;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args)
{SpringApplication.run(Application.class, args);}
}
Spring Boot 6
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
The following code shows the code for auto wired Rest Template object and Bean
creation object in main Spring Boot Application class file −
package com.tutorialspoint.demo;
import org.springframework.beans.factory.annotation.Autowired;
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 {
@Autowired
RestTemplate restTemplate;
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;
Spring Boot 7
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");
}
}
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");
}
}
Properties File
Properties files are used to keep ‘N’ number of properties in a single file to run the
application in a different environment. In Spring Boot, properties are kept in
the application.properties file under the classpath.
The application.properties file is located in the src/main/resources directory. The
code for sample application.properties file is given below −
server.port = 9090
spring.application.name = demoservice
Spring Boot 8
Note that in the code shown above the Spring Boot application demoservice starts
on the port 9090.
YAML File
Spring Boot supports YAML based properties configurations to run the application.
Instead of application.properties, we can use application.yml file. This YAML file
also should be kept inside the classpath. The sample application.yml file is given
below −
spring:
application:
name: demoservice
server:
port: 9090
Externalized Properties
Instead of keeping the properties file under classpath, we can keep the properties in
different location or path. While running the JAR file, we can specify the properties
file path. You can use the following command to specify the location of properties
file while running the JAR −
-Dspring.config.location = C:\application.properties
@SpringBootApplication
@RestController
public class DemoApplication {
@Value("${spring.application.name}")
private String name;
public static void main(String[] args) {
Spring Boot 9
SpringApplication.run(DemoApplication.class, args);
}
@RequestMapping(value = "/")
public String name() {
return name;
}
}
You can see active profile name on the console log as shown below −
2017-11-26 08:13:16.322 INFO 14028 --- [
main] com.tutorialspoint.demo.DemoApplication :
The following profiles are active: dev
Now, Tomcat has started on the port 9090 (http) as shown below −
2017-11-26 08:13:20.185 INFO 14028 --- [
main] s.b.c.e.t.TomcatEmbeddedServletContainer :
Spring Boot 10
You can see active profile name on the console log as shown below −
2017-11-26 08:13:16.322 INFO 14028 --- [
main] com.tutorialspoint.demo.DemoApplication :
The following profiles are active: prod
Now, Tomcat started on the port 4431 (http) as shown below −
2017-11-26 08:13:20.185 INFO 14028 --- [
main] s.b.c.e.t.TomcatEmbeddedServletContainer :
Tomcat started on port(s): 4431 (http)
Spring active profile for application.yml
Let us understand how to keep Spring active profile for application.yml. We can
keep the Spring active profile properties in the single application.yml file. No need
to use the separate file like application.properties.
The following is an example code to keep the Spring active profiles in
application.yml file. Note that the delimiter (---) is used to separate each profile in
application.yml file.
spring:
application:
name: demoservice
server:
port: 8080
---
spring:
profiles: dev
application:
name: demoservice
server:
port: 9090
---
spring:
profiles: prod
application:
name: demoservice
server:
port: 4431
Configure Logback
Logback supports XML based configuration to handle Spring Boot Log
configurations. Logging configuration details are configured in logback.xml file. The
logback.xml file should be placed under the classpath.
You can configure the ROOT level log in Logback.xml file using the code given
below −
<?xml version = "1.0" encoding = "UTF-8"?>
<configuration>
<root level = "INFO">
</root>
</configuration>
You can configure the console appender in Logback.xml file given below.
<?xml version = "1.0" encoding = "UTF-8"?>
<configuration>
<appender name = "STDOUT" class =
"ch.qos.logback.core.ConsoleAppender"></appender>
<root level = "INFO">
<appender-ref ref = "STDOUT"/>
</root>
</configuration>
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>
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 −
Spring Boot 12
@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.
Spring Boot 13
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);
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.
Spring Boot 14
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<>();
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;
Spring Boot 15
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<>();
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 Path variable {id} which defines the
products ID that needs to be deleted.
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<>();
Spring Boot 16
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);
}
}
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<>();
static {
Product honey = new Product();
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(), honey);
@RequestMapping(value = "/products")
public ResponseEntity<Object> getProduct() {
return new ResponseEntity<>(productRepo.values(),
HttpStatus.OK);
}
}
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 {
}
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)
Now, use the code given below to throw the exception from the API.
Spring Boot 19
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);
}
}
For example, you can use an interceptor to add the request header before sending
the request to the controller and add the response header before sending the
response to the client.
To work with interceptor, you need to create @Component class that supports it
and it should implement the HandlerInterceptor interface.
The following are the three methods you should know about while working on
Interceptors −
preHandle() method − This is used to perform operations before sending the
request to the controller. This method should return true to return the
response to the client.
postHandle() method − This is used to perform operations before sending
the response to the client.
afterCompletion() method − This is used to perform operations after
completing the request and response.
Observe the following code for a better understanding −
@Component
public class ProductServiceInterceptor implements
HandlerInterceptor {
@Override
public boolean preHandle(
HttpServletRequest request, HttpServletResponse
response, Object handler) throws Exception {
return true;
}
@Override
public void postHandle(
HttpServletRequest request, HttpServletResponse
response, Object handler,
ModelAndView modelAndView) throws Exception {}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response,
Object handler, Exception exception) throws Exception
{}
}
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
Spring Boot 21
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component
public class ProductServiceInterceptor implements
HandlerInterceptor {
@Override
public boolean preHandle
(HttpServletRequest request, HttpServletResponse response,
Object handler)
throws Exception {
The code for Application Configuration class file to register the Interceptor into
Interceptor Registry – ProductServiceInterceptorAppConfig.java is given below −
package com.tutorialspoint.demo.interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import
org.springframework.web.servlet.config.annotation.InterceptorRegi
stry;
import
org.springframework.web.servlet.config.annotation.WebMvcConfigure
rAdapter;
@Component
public class ProductServiceInterceptorAppConfig extends
WebMvcConfigurerAdapter {
@Autowired
Spring Boot 22
ProductServiceInterceptor productServiceInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(productServiceInterceptor);
}
}
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")
public ResponseEntity<Object> getProduct() {
return new ResponseEntity<>(productRepo.values(),
HttpStatus.OK);
}
}
The code for main Spring Boot application class file 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);
}
}
<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/>
Spring Boot 24
</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>
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 −
@Override
public void doFilter
(ServletRequest request, ServletResponse response,
FilterChain filterchain)
Spring Boot 25
@Override
public void init(FilterConfig filterconfig) throws
ServletException {}
}
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;
Spring Boot 26
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";
}
}
<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>
Spring Boot 27
<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>
Custom Port
In the application.properties file, we can set custom port number for the property
server.port
server.port = 9090
In the application.yml file, you can find as follows −
server:
port: 9090
Random Port
In the application.properties file, we can set random port number for the property
server.port
server.port = 0
In the application.yml file, you can find as follows −
server:
port: 0
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;
Spring Boot 28
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 −
@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("
Spring Boot 29
File Upload
For uploading a file, you can use MultipartFile as a Request Parameter and this
API should consume Multi-Part form data value. Observe the code given below −
@RequestMapping(value = "/upload", method = RequestMethod.POST,
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.springframework.http.MediaType;
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;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class FileUploadController {
@RequestMapping(value = "/upload", method =
RequestMethod.POST,
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
Service Components are the class file which contains @Service annotation. These
class files are used to write business logic in a different layer, separated from
@RestController class file. The logic for creating a service component class file is
shown here −
public interface ProductService {
}
The class that implements the Interface with @Service annotation is as shown −
@Service
public class ProductServiceImpl implements ProductService {
}
Observe that in this tutorial, we are using Product Service API(s) to store, retrieve,
update and delete the products. We wrote the business logic in @RestController
class file itself. Now, we are going to move the business logic code from controller
to service component.
You can create an Interface which contains add, edit, get and delete methods using
the code as shown below −
package com.tutorialspoint.demo.service;
import java.util.Collection;
import com.tutorialspoint.demo.model.Product;
The following code will let you to create a class which implements the
ProductService interface with @Service annotation and write the business logic to
store, retrieve, delete and updates the product.
package com.tutorialspoint.demo.service;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.tutorialspoint.demo.model.Product;
@Service
public class ProductServiceImpl implements ProductService {
private static Map<String, Product> productRepo = new
HashMap<>();
static {
Product honey = new Product();
Spring Boot 31
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(), honey);
}
@Override
public Collection<Product> getProducts() {
return productRepo.values();
}
}
The code here show the Rest Controller class file, here we @Autowired the
ProductService interface and called the methods.
package com.tutorialspoint.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
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;
import com.tutorialspoint.demo.service.ProductService;
@RestController
public class ProductServiceController {
@Autowired
ProductService productService;
@RequestMapping(value = "/products")
Spring Boot 32
productService.updateProduct(id, product);
return new ResponseEntity<>("Product is updated
successsfully", HttpStatus.OK);
}
@RequestMapping(value = "/products/{id}", method =
RequestMethod.DELETE)
public ResponseEntity<Object> delete(@PathVariable("id")
String id) {
productService.deleteProduct(id);
return new ResponseEntity<>("Product is deleted
successsfully", HttpStatus.OK);
}
@RequestMapping(value = "/products", method =
RequestMethod.POST)
public ResponseEntity<Object> createProduct(@RequestBody
Product product) {
productService.createProduct(product);
return new ResponseEntity<>("Product is created
successfully", HttpStatus.CREATED);
}
}
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);
}
}
<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>
Spring Boot 34
<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>