SPRINGBOOTPART02 Flashcards
What is the purpose of ApplicationRunner Interface ?
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"); } }
Command Line Runner is an interface. ?
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"); } }
What is the command for running spring boot using JAr file ?
After creating an executable JAR file, run it by using the command java –jar .
Step 2 − Use the command given in the screenshot given below to change the port number for Spring Boot application by using command-line properties.
Command Line Properties JARFILE
add —server-port
how to change server.port using properties file ?
server. port = 9090
spring. application.name = demoservice
in application.properties ?
What is the activate different profile in springboot ?
By USing diff nomen cleature
application.properties
server.port = 8080
spring.application.name = demoservice
application-dev.properties
server.port = 9090
spring.application.name = demoservice
application-prod.properties
NOTE :- While running pass arument value –spring.avtive.profile == ??
@ControllerAdvice and @ExceptionHandler use of this ?
The @ControllerAdvice is an annotation, to handle the exceptions globally.
The @ExceptionHandler is an annotation used to handle the specific exceptions and sending the custom responses to the client.
@ControllerAdvice public class ProductExceptionController { @ExceptionHandler(value = ProductNotfoundException.class) public ResponseEntity exception(ProductNotfoundException exception) { return new ResponseEntity<>("Product not found", HttpStatus.NOT_FOUND); } }
where we define the version of the Spring boot Application ?
Unlike normal other application we do not define version of each dependency . we just give parent
org.springframework.boot spring-boot-starter-parent 1.5.8.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test
where we define the version of the Spring boot application?
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.
You will have to register this Interceptor with InterceptorRegistry by using WebMvcConfigurerAdapter as shown below −
@Component
public class ProductServiceInterceptorAppConfig extends WebMvcConfigurerAdapter {
@Autowired
ProductServiceInterceptor productServiceInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(productServiceInterceptor);
}
}
Spring Boot - Servlet Filter How to implement it ?
A filter is an object used to intercept the HTTP requests and responses of your application.
Before sending the request to the controller
Before sending a response to the client.
@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 {}
}
What is the purpose of the RestTemplate class. ?
Accessing a third-party REST service inside a Spring application revolves around the use of the Spring RestTemplate class. Given that the RestTemplate class is designed to call REST services,
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.
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 entity = new HttpEntity(headers);
return restTemplate.exchange(" http://localhost:8080/products", HttpMethod.GET, entity, String.class).getBody(); } }
What is the consuem type while uplaoding a file in Spring boot Rest ?
@RequestMapping(value = “/upload”, method = RequestMethod.POST,
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String fileUpload(@RequestParam(“file”) MultipartFile file)
What is the HeaderResponse type for downloading the the file ?
HttpHeader Content-Disposition
headers.add(“Content-Disposition”, String.format(“attachment; filename="%s"”, file.getName()));
What is the 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.
how to Enable Enable CORS in SpringBoot ?
We need to set the origins for RESTful web service by using @CrossOrigin annotation for the controller method.
@RequestMapping(value = "/products") @CrossOrigin(origins = "http://localhost:8080")
public ResponseEntity getProduct() {
Global CORS Configuration
We need to define the shown @Bean configuration to set the CORS configuration support globally to your Spring Boot application.
@Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/products").allowedOrigins("http://localhost:9000"); } }; }
Spring Boot - Scheduling ? Explain
Scheduling is a process of executing the tasks for the specific time period. Java Cron expressions are used to configure the instances of CronTrigger, a subclass of org.quartz.Trigger.
The @EnableScheduling annotation is used to enable the scheduler for your application. This annotation should be added into the main Spring Boot application class file.
@SpringBootApplication
@EnableScheduling
public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } The @Scheduled annotation is used to trigger the scheduler for a specific time period.
@Scheduled(cron = “0 * 9 * * ?”)
public void cronJobSch() throws Exception {
}