Springapplication Springbootapplication: Import I Mport
Springapplication Springbootapplication: Import I Mport
Springapplication Springbootapplication: Import I Mport
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
SpringApplication.run(DemoApplication.class, args);
@SpringBootApplication
@Override
return application.sources(DemoApplication.class);
SpringApplication.run(DemoApplication.class, args);
}
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
@Override protected
SpringApplicationBuilderconfigure(SpringApplicationBuilderapplication) {
return application.sources(DemoApplication.class);
SpringApplication.run(DemoApplication.class, args);
@RequestMapping(value = "/")
}
}
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.
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.
Step 1 − After creating an executable JAR file, run it by using the command java –jar
<JARFILE>.
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
Code :-
@SpringBootApplication
@RestController
@Value("${spring.application.name}")
SpringApplication.run(DemoApplication.class, args);
@RequestMapping(value = "/")
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 −
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
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.
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 −
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 −
Code :-
@RestController
static {
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(), honey);
almond.setId("2"); almond.setName("Almond");
productRepo.put(almond.getId(), almond);
productRepo.remove(id);
productRepo.remove(id);
product.setId(id);
productRepo.put(id, product);
productRepo.put(product.getId(), product);
Return new ResponseEntity<>("Product is created
successfully",HttpStatus.CREATED);
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.
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)
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
static {
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(), honey);
almond.setId("2");
almond.setName("Almond");
productRepo.put(almond.getId(), almond);
if(!productRepo.containsKey(id))
productRepo.remove(id);
product.setId(id);
productRepo.put(id, product);
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.
@Component
@Override
public boolean preHandle
throws Exception {
return true;
@Override
} @Override
The code for Application Configuration class file to register the Interceptor into
Interceptor Registry – ProductServiceInterceptorAppConfig.java is given below −
@Component
@Autowired
ProductServiceInterceptor productServiceInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(productServiceInterceptor); }
@RestController
static{
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(),honey);
almond.setId("2");
almond.setName("Almond");
productRepo.put(almond.getId(), almond);
@RequestMapping(value ="/products")
publicResponseEntity<Object> getProduct(){
}
Spring Boot - Servlet Filter
By using filter, we can perform two operations at two instances −
@Component\
@Override
@Override
throwsIOException, ServletException {
System.out.println("Remote Host:"+request.getRemoteHost());
System.out.println("Remote Address:"+request.getRemoteAddr());
filterchain.doFilter(request, response);
@Override
@SpringBootApplication
SpringApplication.run(DemoApplication.class, args);
@Bean
GET
Consuming the GET API by using RestTemplate - exchange() method
You will have to follow the given points to consume the API −
@RestController
@Autowired
RestTemplate restTemplate;
@RequestMapping(value = "/template/products")
return restTemplate.exchange("
POST
Consuming POST API by using RestTemplate - exchange() method
You will have to follow the points given below to consume the API −
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
@Autowired RestTemplaterestTemplate;
File Upload
you can use MultipartFile as a Request Parameter and this API should consume Multi-
Part form data value.
@RestController
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
fout.write(file.getBytes());
fout.close();
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.
headers.add("Expires","0");
ResponseEntity<Object>
responseEntity =
ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType( Medi
aType.parseMediaType("application/txt")).body(resource);
return responseEntity;
}
The class that implements the Interface with @Service annotation is as shown −
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
static {
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(), honey);
almond.setId("2");
almond.setName("Almond");
productRepo.put(almond.getId(), almond);
@Override
productRepo.put(product.getId(), product);
@Override
productRepo.remove(id);
product.setId(id);
productRepo.put(id, product);
@Override
productRepo.remove(id);
return productRepo.values(); }
The code here show the Rest Controller class file, here we @Autowired the
ProductService interface and called the methods.
@RestController
@RequestMapping(value = "/products")
public ResponseEntity<Object>
productService.updateProduct(id, product);
return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK);
productService.deleteProduct(id);
productService.createProduct(product);
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
@RequestMapping(value = "/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>
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.
RESTful web service application should allow accessing the API(s) from the 8080 port.
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")
return null;