Friday, December 27, 2019

Basic Spring Boot Interview Questions



What is a Spring boot? How it benefits to develop the rest full web service?

Spring Boot is an open source Java-based spring framework, which ease to develop a stand-alone and production ready micro service-based applications:
  • 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.
Spring boot ease and simplify the development of rest full web service and provide a quicker development technique by using the key features provided by spring boot framework.

What are the key features of spring boot which makes Spring boot superior over the JAX-RS?

There are significant advantages of using spring boot over the JAX-RS which is listed below.
  • 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.
All this advantage makes spring boot is one of best alternative to develop the microservices application, along with one of the key benefits is, to make it compatible to use the other framework like messaging services, hibernate and spring cloud.

Why do we encourage to use the spring boot over the other framework?

Spring boot provides good compatibility with other spring frameworks which is used to provide the security, persistency features. Spring boot provides good support with docker containerization, which makes it a good choice to deploy the microservice based application and easy to maintain.
  • 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.  
Spring boot comes with spring cloud framework, which has many libraries which are used to handle all types of nonfunctional requirement, which is usually not available in other frameworks.

How spring boot work internally?

Spring boot provides many abstraction layers to ease the development, underneath there are vital libraries which work for us. 
Below is the key function performing 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. 
Considering above there are other internal functions which play a significant role in spring boot.

What is the important dependency of spring boot application?

Below are the key dependencies which you need to add in maven based or Gradle based applications, to make the application compatible to use spring boot functionality. 
  • spring-boot-starter-parent
  • spring-boot-starter-web
  • spring-boot-starter-actuator
  • spring-boot-starter-security
  • spring-boot-starter-test
  • spring-boot-maven-plugin
These dependencies come with associated child dependencies, which are also downloaded as a part of parent dependencies. 

 

What is a Spring boot starter?
Spring boot starter comprises of templates which provide a Rapid Application Development, spring boot starter contains a combination of all the relevant transitive dependencies.  
  • 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.
Below are some of the popular Spring boot starters:
  • 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?

Spring boot Initilizr is a web application which use to generate the common templates of spring boot application according to the configuration providing in the user interface.

What is Spring boot CLI?

Spring boot CLI is a command line interface, which use and run test the microservices application based on spring boot.
What is a Spring-boot interceptor? Why do we need this features and is there any real use case scenario where spring boot interceptor fits?
Spring boot interceptor is typically used to intercept the request and response call made by the UI and microservices-based application, the need of this to add, filter, modified the information contain in request and response.
  • 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.
The real-world use case of spring-boot interceptor is authentication and authorization, where   we filter the information from the request which contain the credential information which use to authenticate and other information like role which require authorization. 

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



What is a Spring Boot Actuator? What are the features provided and how you can customize or add more?

 

The actuator provides built-in features to your application which are production-ready. It provides web endpoints for each of this feature. Some of the most common Spring Boot Actuator endpoints:
  • /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.
For example, when using MicroServices, you will definitely a health check for your microservice as your service registry/Load Balancer need to be updated with only live or healthy services so that any incoming request to your application goes to live node/server only. Instead of building your own health endpoint, you can just import the Spring Boot Actuator and use the built-in health endpoint.
If you need to your own health endpoint, you can do so by implementing health() method from org.springframework.boot.actuate.health.HealthIndicator.
To implement your own endpoint, you can implement org.springframework.boot.actuate.endpoint interface.
With Spring Boot Actuator 2.X, all endpoints except health and Info are disabled. To enable them you need to  set management.endpoints.web.exposure.include=*.

 

How do you make sure your changes are loaded without restarting the Spring Boot Application when running in Embedded Server mode?

 

You can achieve this by adding a starter dependency for DEV tools.

spring-boot-devtools
This is a very helpful feature in development, as it gives immediate feedback for code changes. This enhances the productivity of developers to a great extent by saving time in restarts.
This is not a production-ready tool or feature and will be automatically disabled when running in production.
Applications using DevTools restart whenever a file on the classpath is modified.
Spring Boot DevTools provide the following additional features :
  1. 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.
  2. Remote Debugging via HTTP 
Explain how you will go about Security in Spring Boot Application?

With a Spring Boot Application, you can fallback to Spring Security. Include the Spring Security Boot Starter :

 spring-boot-starter-security
 

You can go with HTTP basic or form login.
To update the username or password , override the following properties in application properties file :
Spring.security.user.name = username1
Spring.security.user.password = password1
To enable method level security, you can use @EnableGlobalMethodSecurity.
To disable default Security configuration in-built, you need to exclude SecurityAutoConfiguration class as follows :
@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
public class SpringBootApplication1 {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootApplication1.class, args);
    }
}
This can be also achieved by adding following to properties file :
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
@ConfigurationTo Override default Security you can implement WebSecurityConfigurerAdapter class , 
for example :
@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();
    }
}
@EnableWebSecurity is optional if the default security configuration is disabled.
Oauth2 is commonly used for authorization. To integrated OAuth2:
  • Add a starter for Oauth2
  • Use @EnableAuthrizationServer
  • Use @EnableResourceServer in an application where resource located 
  • On Client Side, use either of  @EnableOAuth2Sso or @EnableOAuth2Client.
Explain the difference between Embedded Server & War file.

 

Embedded Server (in context of Spring Boot) means a Web Server that comes in-built with Spring Boot. Spring Boot supports 3 web servers :
  • 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.
If you would like to disable the web starter, you can do so by adding the following property to application.properties :spring.main.web-application-type=none
This is how you can customize/override various default properties associated with the webserver:
  • Port 
You can override port by specifying it in application properties as :
server.port =8081
You can also override by including it as an environment variable(SERVER_PORT=8081).
To disable , HTTP port set :
server.port=-1
While, if you want to look for the best open port, use :
server.port=0
  • HTTP response Compression 
Use the following in property file :
server.compression.enabled=true
  • SSL 
SSL can be configured by setting appropriate properties in application.properties file , for example :
server.ssl.key-store=classpath:keystore.jks
server.ssl.key-store-password=secret
server.ssl.key-password=another-secret


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

  1. 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.
  2. Registering Interceptors: Interceptors are registered through the WebMvcConfigurer interface. You can add custom interceptors using the addInterceptors method.

 


No comments:

Post a Comment