Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Springapplication Springbootapplication: Import I Mport

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 25

Spring Boot:

Main Method
The main method should be writing the Spring Boot Application class. This class should
be annotated with @SpringBootApplication.

Import org.springframework.boot.SpringApplication;i

mport org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class DemoApplication {

public static void main(String[] args) {

SpringApplication.run(DemoApplication.class, args);

Spring Boot Servlet Initializer

the Spring Boot Application @SpringBootApplication class extend the


SpringBootServletInitializerclass. Spring Boot Servlet Initializer class file allows you to
configure the application when it is launched by using Servlet Container.

@SpringBootApplication

publicclass 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);
}

Setting Main Class


In Spring Boot, we need to mention the main class that should start in the build file. For
this purpose, you can use the following pieces of code −

For Maven, add the start class in pom.xml properties as shown below −

<start-class>com.ib.DemoApplication</start-class>

Simple Rest Endpoint in Spring Boot Application class file using the code as shown
below −

@SpringBootApplication

@RestController

public class DemoApplication extends SpringBootServletInitializer {

@Override protected
SpringApplicationBuilderconfigure(SpringApplicationBuilderapplication) {

return application.sources(DemoApplication.class);

public static void main(String[] args) {

SpringApplication.run(DemoApplication.class, args);

@RequestMapping(value = "/")

public String hello() {

return "Hello World from Tomcat";

}
}

Beans and Dependency Injection

In Spring Boot, we can use Spring Framework to define our beans and their dependency
injection. The @ComponentScan annotation is used to find beans and the corresponding
injected with @Autowired annotation.

Spring Boot - Runners

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.

Spring Boot - Application Properties


Command Line Properties

Step 1 − After creating an executable JAR file, run it by using the command java –jar
<JARFILE>.

Java -jar abc.jar --server.port=9090


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

YAML File
Spring Boot supports YAML based properties configurations to run the application.
Instead of application.properties, we can use application.ymlfile. 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

Use of @Value Annotation


@Value("${property_key_name}")
Ex:-
@Value("${spring.application.name}")

Code :-

@SpringBootApplication

@RestController

public class DemoApplication {

@Value("${spring.application.name}")

private String name;

public static void main(String[] args) {

SpringApplication.run(DemoApplication.class, args);

@RequestMapping(value = "/")

public String name() {

returnname;

Note − If the property is not found while running the application, Spring Boot throws the
Illegal Argument exception as Could not resolve placeholder 'spring.application.name' in
value "${spring.application.name}".

To resolve the placeholder issue, we can set the default value for the property using thr
syntax given below −

@Value("${property_key_name:default_value}")

@Value("${spring.application.name:demoservice}")
Spring active profile in application.properties
f you want to use profile based properties, we can keep separate properties file for each
profile as shown below −

application.properties

server.port = 8080
spring.application.name = demoservice

application-dev.properties

server.port = 9090
spring.application.name = demoservice

application-prod.properties

server.port = 4431
spring.application.name = demoservice

While running the JAR file, we need to specify the spring active profile based on each
properties file. By default, Spring Boot application uses the application.properties file.
The command to set the spring active profile is shown below −

Java -jar abc.jar --spring.profiles.active=dev

Spring Boot - Logging

Console Log Output


java –jar demo.jar --debug

You can also add the debug mode to your application.properties file as shown here −

debug = true
File Log Output

logging.path = /var/tmp/

You can specify the own log file name using the property shown below −

logging.file = /var/tmp/mylog.log

Note − files will rotate automatically after reaching the size 10 MB.

Log Levels
logging.level.root = WARN

Spring Boot - Building RESTful Web Services

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>

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) {
}

Code :-

@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.DELETE)


publicResponseEntity<Object>delete(@PathVariable("id") Stringid){

productRepo.remove(id);

return new ResponseEntity<>("Product is deleted successsfully",HttpStatus.OK);

@RequestMapping(value ="/products/{id}",method =RequestMethod.PUT)


publicResponseEntity<Object> updateProduct(@PathVariable("id") Stringid,
@RequestBody Product product) {

productRepo.remove(id);

product.setId(id);
productRepo.put(id, product);

Return newResponseEntity<>("Product is updated successsfully",HttpStatus.OK);

@RequestMapping(value = "/products",method = RequestMethod.POST)


publicResponseEntity<Object>createProduct(@RequestBodyProduct product){

productRepo.put(product.getId(), product);
Return new ResponseEntity<>("Product is created
successfully",HttpStatus.CREATED);

@RequestMapping(value ="/products") publicResponseEntity<Object>getProduct() {

return newResponseEntity<>(productRepo.values(), HttpStatus.OK);

Spring Boot - Exception Handling


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.

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.

Public class ProductNotfoundException extendsRuntimeException {

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.

@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 ProductNotFoundExceptionclass.

@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);

Spring Boot - Interceptor

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 {

System.out.println("Pre Handle method is Calling");

return true;

@Override

public void postHandle(HttpServletRequest request, HttpServletResponse response,

Object handler, ModelAndView modelAndView) throws Exception {

System.out.println("Post Handle method is Calling");

} @Override

public void afterCompletion

(HttpServletRequest request, HttpServletResponse response, Object

handler, Exception exception) throws Exception {

System.out.println("Request and Response is completed"); }

The code for Application Configuration class file to register the Interceptor into
Interceptor Registry – ProductServiceInterceptorAppConfig.java is given below −

@Component

public class ProductServiceInterceptorAppConfig extends WebMvcConfigurerAdapter {

@Autowired

ProductServiceInterceptor productServiceInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {

registry.addInterceptor(productServiceInterceptor); }

The code for Controller class file ProductServiceController.java is given below −

@RestController

public class ProductServiceController {

private static Map<String, Product> productRepo = new HashMap<>();

static{

Producthoney = new Product();

honey.setId("1");

honey.setName("Honey");

productRepo.put(honey.getId(),honey);

Product almond = newProduct();

almond.setId("2");

almond.setName("Almond");

productRepo.put(almond.getId(), almond);

@RequestMapping(value ="/products")

publicResponseEntity<Object> getProduct(){

return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);

}
Spring Boot - Servlet Filter
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.

In doFilter() method, we have added the System.out.println statements to print the


remote host and remote address.

@Component\

public class SimpleFilter implements Filter {

@Override

public void destroy() {}

@Override

public void doFilter(ServletRequest request,ServletResponse response,


FilterChainfilterchain)

throwsIOException, 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 {}}

Spring Boot - Rest Template


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.

@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

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

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 RestTemplaterestTemplate;

@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();
}

Spring Boot - File Handling

File Upload

you can use MultipartFile as a Request Parameter and this API should consume Multi-
Part form data value.

@RestController

public class FileUploadController {

@RequestMapping(value = "/upload", method = RequestMethod.POST,

consumes = MediaType.MULTIPART_FORM_DATA_VALUE)

public String fileUpload(@RequestParam("file") MultipartFile file) throws


IOException {

File convertFile = new File("/var/tmp/"+file.getOriginalFilename());


convertFile.createNewFile();

FileOutputStream fout = new FileOutputStream(convertFile);

fout.write(file.getBytes());

fout.close();

return "File is upload successfully"; }

}@RequestMapping(value = "/download", method = RequestMethod.GET)

public ResponseEntity<Object> downloadFile() throws IOException {

String filename = "/var/tmp/mysql.png";

File file = new File(filename);

InputStreamResource resource = new InputStreamResource(new


FileInputStream(file));
HttpHeaders headers = new HttpHeaders();

headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"",


file.getName()));

headers.add("Cache-Control", "no-cache, no-store, must-revalidate");

headers.add("Pragma", "no-cache");

headers.add("Expires", "0");

ResponseEntity<Object>

responseEntity =
ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(

MediaType.parseMediaType("application/txt")).body(resource);

return responseEntity;

File Download
you should use InputStreamResource for downloading a File. We need to set the
HttpHeader Content-Disposition in Response and need to specify the response Media
Type of the application.

Note − In the following example, file should be available on the specified path where the
application is running.

@RequestMapping(value = "/download", method = RequestMethod.GET)

Public ResponseEntity<Object> downloadFile() throws IOException {

String filename = "/var/tmp/mysql.png";

File file = new File(filename);


InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
HttpHeaders headers = new HttpHeaders();

headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"",


file.getName()));

headers.add("Cache-Control", "no-cache, no-store, must-revalidate");


headers.add("Pragma", "no-cache");

headers.add("Expires","0");

ResponseEntity<Object>

responseEntity =
ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType( Medi
aType.parseMediaType("application/txt")).body(resource);

return responseEntity;
}

Spring Boot - Service Components


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 {}

Code full with diffrent layers:-

public interface ProductService {

public abstract void createProduct(Product product);

public abstract void updateProduct(String id, Product product);

public abstract void deleteProduct(String id);


public abstractCollection<Product>getProducts();}

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.

@Service

public class ProductServiceImpl implements ProductService {

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);

@Override

public void createProduct(Product product) {

productRepo.put(product.getId(), product);

@Override

public void updateProduct(String id, Product product) {

productRepo.remove(id);
product.setId(id);

productRepo.put(id, product);

@Override

public void deleteProduct(String id) {

productRepo.remove(id);

@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.

@RestController

public class ProductServiceController {

@Autowired ProductService productService;

@RequestMapping(value = "/products")

public ResponseEntity<Object> getProduct() {

return new ResponseEntity<>(productService.getProducts(), HttpStatus.OK);

@RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)

public ResponseEntity<Object>

updateProduct(@PathVariable("id") String id, @RequestBody Product product) {

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);


}

Spring Boot - Thymeleaf


Web Application
You can use Thymeleaf templates to create a web application in Spring Boot. You will
have to follow the below steps to create a web application in Spring Boot by using
Thymeleaf.

Use the following code to create a @Controller class file to redirect the Request URI to
HTML file −

import org.springframework.stereotype.Controller;import
org.springframework.web.bind.annotation.RequestMapping;

@Controller

public class WebController {

@RequestMapping(value = "/index")

public String index() {


return "index";

In the above example, the request URI is /index, and the control is redirected into the
index.html file. Note that the index.html file should be placed under the templates
directory and all JS and CSS files should be placed under the static directory in
classpath. In the example shown, we used CSS file to change the color of the text.

Maven users can add the following dependency into the pom.xml file −

<dependency>

<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-
thymeleaf</artifactId>

</dependency>

Spring Boot - CORS Support


Cross-Origin Resource Sharing (CORS) is a security concept that allows restricting the
resources implemented in web browsers. It prevents the JavaScript code producing or
consuming the requests against different origin.

For example, your web application is running on 8080 port and by using JavaScript you
are trying to consuming RESTful web services from 9090 port. Under such situations,
you will face the Cross-Origin Resource Sharing security issue on your web browsers.

Two requirements are needed to handle this issue −

RESTful web services should support the Cross-Origin Resource Sharing.

RESTful web service application should allow accessing the API(s) from the 8080 port.

Enable CORS in Controller Method

We need to set the origins for RESTful web service by using @CrossOrigin annotation for the controller
method. This @CrossOrigin annotation supports specific REST API, and not for the entire application.

@RequestMapping(value = "/products")
@CrossOrigin(origins = "http://localhost:8080")

public ResponseEntity<Object> getProduct() {

return null;

You might also like