- Spring boot is a combination of spring framework, embedded HTTP servers and configuration annotation
- It
     follows “Opinionated Defaults Configuration” Approach to avoid lot of boilerplate
     code and configuration to improve Development, Unit Test and Integration
     Test Process.
- Spring
     boot reduce Development, Unit Test and Integration Test time and to ease
     the development of Production ready web applications.
- Spring
     boot comes with auto configuration, for instance, we must mention the
     dependency it will configure the spring boot accordingly, just we need to
     add the @EnableAutoConfiguration annotation
- Spring
     boot support both Java and Groovy. 
- Spring
     boot also support Spring Initializer to generate the base project.
- @SpringBootApplication
     annotation requires to configure the spring boot application.
- Spring
     boot embedded HTTP server generally run on 8081 server port.
What are the key features of
spring boot which makes Spring boot superior over the JAX-RS?
- Easy deployment
- Simple scalability
- Compatible with Containers
- Minimum configuration
- Lesser production time
- Easy to understand, develop and configure the spring application
- Increase the productivity 
- Reduce the development time.
- Provide the health check and monitoring feature.
- Easy to orchestrate using docker.
Why do we encourage to use the
spring boot over the other framework?
- Provide the easiest way to configure the java beans.
- Provide a powerful batch processing and manage rest endpoints.
- Provide auto-configuration mechanism, that means no manual
     configuration needed. 
- Provide annotation-based configuration, so no need to configure the
     xml file manually.
- Ease the dependency management.
- It includes the Embedded servlet container.  
How spring boot work internally?
- Using @EnableAutoConfigure annotation the spring boot application
     configures the spring boot application automatically. 
- E.g. If you need MySQL DB in your project, but you haven’t
     configured any database connection, in that case, Spring boot auto
     configures as in memory database.
- The entry point of spring boot application is a class which
     contains @SpringBootApplication annotation and has the main
     method.
- Spring boot scan all the components included in the project by using
     @ComponentScan annotation.
- Let’s say we need the Spring and JPA for database connection, then
     we no need to add the individual dependency we can simply add the
     spring-boot-starter-data-jpa in the project.
- Spring boot follows the naming convention for dependency like
     spring-boot-starter. 
What is the important
dependency of spring boot application?
- spring-boot-starter-parent
- spring-boot-starter-web
- spring-boot-starter-actuator
- spring-boot-starter-security
- spring-boot-starter-test
- spring-boot-maven-plugin
- Spring boot starter is a jar file which predominantly solves the
     auto-dependency resolution in a spring boot application. 
- Spring boot starter follows the unified pattern, like every
     dependency start with spring-boot-starter-X, where X will be the name of dependencies.  
- For instance, if we add the dependency like spring-boot-starter-web, the spring boot starter will internally resolve and download all
     the associated dependencies, add to the application. 
- Spring boot also checks and resolves the transitive dependencies
     internally.
- Spring-boot-starter-web
- Spring-boot-starter-mvc
- Spring-boot-starter-security
- Spring-boot-starter-jpa
- Spring-boot-starter-tomcat
- Spring-boot-starter-jetty
- Spring-boot-starter-json
What is Spring boot Initilizr?
What is Spring boot CLI?
- Interceptor in Spring Boot one can use to add the request header
     before sending the request to the controller 
- Interceptor in Spring Boot can add the response header before
     sending the response to the client.
- Spring boot works on the below technique. 
- Before sending the request to the controller
- Before sending the response to the client
- After completing the request and response.
What are the important annotation
for Spring rest? What is the use case of this annotation?
- @RestController: Define at class level, so that spring container
     will consider as RestENd point
- @RequestMapping(value = "/products"): Define the REST URL
     for method level.
- @PathVariable:  Define as a method argument
- @RequestBody:  Define as a method argument
- @ResponseEntity: To convert the domain object into the response
     format
- @hasAuthority:     To grant the access of corresponding
     endpoints 
- @GetMapping: To make endpoint compatible for get request.
- @PostMapping: To make endpoint compatible for post request.
- @PutMapping: To make endpoint compatible for put request.
- @DeleteMapping: To make endpoint compatible for delete request.
- @ResponseStatus:  To generate the HTTP status.
- @ResponseBody:  To Generate the response message
- /health: It shows application health information.
- /info: It shows arbitrary application info.
- /metrics: It shows all metrics related information for the current
     application.
- /trace: It shows trace information for last few HTTP requests.
- /beans: It lists all Spring beans in your application.
- /threaddump: Performs thread dump.
- /env: Displays a list of properties in the current environment.
spring-boot-devtools
- You may need a way to configure global settings which are not tied
     to a particular application. Spring-boot-dev tools supports this by
     providing a global file is called .spring-boot-dev tools.properties. You
     can store all such global settings in this file.
- Remote Debugging via HTTP
 spring-boot-starter-security 
 
You can go with HTTP basic or form login.
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
@EnableWebSecurity
public class BasicConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth)
      throws Exception {
        auth
          .inMemoryAuthentication()
          .withUser("username")
            .password("password1")
            .roles("GUEST")
            .and()
          .withUser("admin")
            .password("admin")
            .roles("GUEST", "ADMIN");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        HTTP
          .authorizeRequests()
          .anyRequest()
          .authenticated()
          .and()
          .httpBasic();
    }
}
- Add a starter for Oauth2
- Use @EnableAuthrizationServer
- Use @EnableResourceServer in an application where resource
     located 
- On Client Side, use either of  @EnableOAuth2Sso
     or @EnableOAuth2Client. 
- Tomcat (This is a default web server . In fact, when you include
     Spring Boot web starter dependency, you get this without any more
     configuration)
- Jetty: To override the default and include this, you can use
     spring-boot-starter-jetty dependency. At the same time, make sure you
     exclude tomcat web server dependency (default).
- Undertow: This is another webserver supported by Spring Boot. To
     include this, you can use spring-boot-starter-undertow dependency.
- Port 
- HTTP response Compression 
- SSL 
What is the purpose of the @SpringBootApplication
annotation? 
The @SpringBootApplication annotation is a convenience
annotation that combines three essential Spring annotations:
 @Configuration:
- This
     annotation allows you to define beans and configuration settings.
 @EnableAutoConfiguration:
- This
     annotation tells Spring Boot to automatically configure your application
     based on the dependencies present on the classpath. It tries to guess and
     configure beans you are likely to need, such as data sources, view
     resolvers, and more, based on the project setup and available libraries.
@ComponentScan:
- This
     annotation enables component scanning, allowing Spring to discover and
     register beans (components) within the specified package and its
     sub-packages. By default, it scans the package of the class where @SpringBootApplication
     is declared and its sub-packages.
How do you handle different configurations
for various environments in Spring Boot?
Answer: Spring Boot uses
profiles to manage configurations for different environments. You can define
profile-specific properties in application-{profile}.properties or application-{profile}.yml
files. Profiles are activated using the spring.profiles.active property.
What is the difference between @Component,
@Service, @Repository, and @Controller?
- @Component:
     A generic stereotype for any Spring-managed component. It can be used for
     any class.
- @Service:
     A specialization of @Component used for service layer components. It
     indicates that the class performs service tasks.
- @Repository:
     A specialization of @Component used for DAO (Data Access Object) classes.
     It includes exception translation to Spring’s DataAccessException.
- @Controller:
     A specialization of @Component used in the presentation layer for web
     controllers. It is used to handle HTTP requests and return views.
The @Component annotation
We can use @Component annotation in our application to
declare any class as the Spring’s managed components. Spring internally picks
up and registers beans with @Component and doesn’t look for @Service and
@Repository in general. Because the @Service and @Repository are also annotated
with @Component.
- The @Component annotation
     is a generic stereotype annotation used to designate any Spring-managed
     component.
- It
     indicates that the annotated class is a candidate for auto-detection and
     bean registration during the component scanning process.
- It’s
     a general-purpose annotation and can be used to annotate any class that
     should be managed by the Spring container.
In simple words, the classes under the @ComponentScan
path annotated with @Component annotation will be registered as a Bean in
Spring ApplicationContext. You can use the instance of such bean using the
@Inject or @Autowired annotations.
In short, the @Component annotation is used to declare any general class as a Spring-managed bean class, @Service is used to declare any class as a Business logic (Service) class and @Repository is for the DTO, DAO, or repository class where the database operations are performed. This also demonstrates about @Componet vs. @Repository and @Service. While @Component is a generic stereotype annotation, @Repository and @Service are more specific stereotypes used to annotate classes with well-defined roles within a Spring application. Choosing the appropriate annotation helps to convey the intended purpose of the annotated class and provides additional metadata for Spring’s component scanning and auto-wiring mechanisms.
@Component vs @Bean
The @Bean annotation is a method-level annotation,
whereas @Component is a class-level annotation. The @Component annotation
doesn't need to be used with the @Configuration annotation, whereas the @Bean
generic annotation has to be used within a class annotated with @Configuration
.
How would you handle exceptions in a Spring Boot REST API?
Exceptions in Spring Boot REST APIs can be handled
using:
- @ExceptionHandler:
     To handle specific exceptions within a controller.
- @ControllerAdvice:
     To handle exceptions globally across all controllers.
- ResponseEntityExceptionHandler:
     A base class provided by Spring Boot to customize error responses.
Example:
@ControllerAdvice
public class
GlobalExceptionHandler {
   
@ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ErrorResponse>
handleResourceNotFound(ResourceNotFoundException ex) {
        ErrorResponse error = new
ErrorResponse("Resource not found", ex.getMessage());
        return new
ResponseEntity<>(error, HttpStatus.NOT_FOUND);
    }
}
What is Spring Boot
interceptors?
In Spring Boot,
interceptors are used to preprocess or postprocess HTTP requests and responses.
They provide a way to perform tasks such as logging, modifying requests and
responses, authentication, and authorization. Interceptors are a powerful
feature for adding cross-cutting concerns in a web application.
Key Concepts
- Interceptor Interface:
     Spring provides the HandlerInterceptor interface for creating
     interceptors. This interface has three main methods:
- preHandle(HttpServletRequest
      request, HttpServletResponse response, Object handler):
      Called before the request is handled by the controller. Can be used to
      modify the request or perform operations before the controller method is
      invoked.
- postHandle(HttpServletRequest
      request, HttpServletResponse response, Object handler, ModelAndView
      modelAndView): Called after the controller method
      has been executed but before the view is rendered. Can be used to modify
      the ModelAndView object.
- afterCompletion(HttpServletRequest
      request, HttpServletResponse response, Object handler, Exception ex):
      Called after the view is rendered and the request has been completed. Can
      be used for cleanup tasks or logging.
- Registering Interceptors:
     Interceptors are registered through the WebMvcConfigurer interface. You
     can add custom interceptors using the addInterceptors method.

 
No comments:
Post a Comment