The most classic 20 Spring Boot interview questions, more than 95% will be asked, not convinced to fight

Top 20 Frequently Asked Questions in Spring Boot Technical Interviews.

1. What are the characteristics of Spring Boot?

Spring Boot is an extension to Spring that eliminates the boilerplate configuration required to set up Spring applications.

  • automatic configuration

This is the most important feature of Spring Boot. This greatly eliminates manual configuration. The base framework comes with a built-in library called auto-configure that does this work for us. It detects the presence of certain classes and their presence on the classpath, and auto-configures them for us.

For example: — When we add spring-boot-starter-web dependency in our project, Spring Boot auto-configuration looks to see if Spring MVC is in the classpath. It automatically configures dispatcherServlet, default error pages and web jars. — Similarly, when we add
the spring-boot-starter-data-jpa dependency, we see Spring Boot auto-configuration, auto-configuring a data source and an entity manager.

  • Embedded Tomcat web server

Spring Boot ships with Tomcat server by default. Therefore, we don't need to configure a server to run the application (if our preferred server is Tomcat).

  • Getting Started POM

Spring Boot itself provides a number of startup POMs to accomplish the most common tasks in development life. We can rely on them and the framework itself without going to third-party libraries. I list some of them here.

  1. spring-boot-starter-web: create a REST API
  2. spring-boot-starter-data-jpa: connect to SQL database
  3. spring-boot-starter-data-mongodb: connect to MongoDB
  4. spring-boot-starter-aop: Applying Aspect-Oriented Programming concepts
  5. spring-boot-starter-security: implements security such as role-based authentication
  6. spring-boot-starter-test: Implement unit testing
  • Actuator API

Spring Boot Actuator is a sub-project of the Spring Boot framework. It allows us to view insights and metrics and monitor running applications through a set of API endpoints. We don't need to create them manually.

  1. Database Statistics: Datasource Usage
  2. CPU memory usage
  3. GC cycle
  4. Tracing HTTP requests
  • Spring Boot initializer

This is a web-based UI that primarily provides the ability to create a new Spring Boot project with available dependencies and download the project created as a zip. So we don't have to create it from scratch. All the basic structure of the project is already in this downloaded zip. The Spring Initializer is provided as an IDE plugin, also under a different name.

For example: for IntelliJ - the plugin is Spring Assistant or Spring Initializer.

2. Do you know how the "@SpringBootApplication" annotation works internally?

A Spring Boot application is executed using this annotation. Actually it's a combination of 3 other annotations:

ComponentScan、EnableAutoConfiguration和Configuration。

@SpringBootApplication = @ComponentScan + @EnableAutoConfiguration + @Configuration
  • "@Configuration" - All annotated classes are considered as Spring Boot's AD configuration and they are eligible to create beans and return to the IOC container.
  • "@ComponentScan" - All annotated classes will be scanned through packages (where to look) and help create instances of these classes.
  • "@EnableAutoConfiguration" - this is the magic annotation. This looks for the classpath. The base framework comes with a built-in library called auto-configure that does this work for us. It detects the presence of certain classes and their presence on the classpath, and auto-configures them for us. I put a snapshot of the library below. If you head to the spring.factories file, you'll see the available class configurations.

 

The picture above is the automatic configuration dependent JAR

Suppose we add a JPA dependency: Spring Boot checks the class-path to see what is available and
the properties defined in the application.properties/yml file. Here will be the database URL and credentials.

The JPA Repository classes are also annotated with some conditional annotations, such as "@ConditionalOnBean", "@ConditionalOnClass", according to these rules, the configuration is generated.

3. What is a bean?

Beans are just plain Java objects. In the context of Spring Boot, they are considered Java objects + objects that are automatically initialized at application startup and managed by the Spring IOC container. We have "@Bean" annotation to achieve this.

4. What is Inversion of Control (IOC) in Spring?

Inversion of control:

The principle of transferring control of an object or part of a program to a container or framework. We use it most often in  the context of object-oriented  programming. Simply put, control is handled by the framework, not us - the inverse of program control flow. The opposite is the movement of Tao.

Spring IOC container:

A container that creates objects, configures and assembles their dependencies, and manages their entire lifecycle. It uses Dependency Injection (DI) to manage the components that make up the application.

5. How do we implement dependency injection in Spring Boot?

DI — pass an object as a dependency to another object

In Spring Boot, we can use the "@Autowired" annotation to achieve this. The Spring IOC container will then create the objects on our behalf. Usually, at the controller layer we inject the service and at the service layer we inject the repository to use this annotation.

6. What are the layers of Spring Boot microservices?

  • Controller layer: all controllers with defined methods for API endpoints. Classes are annotated with the "@RestController" annotation.
  • Repository/DAO layer: All repository interfaces are included in this layer for querying the selected database (SQL/no SQL). Interfaces are annotated with the "@Repository" annotation.
  • Service Layer: All business logic is contained here. It is usually at this layer that the DAO layer is accessed to perform some operations. Classes are annotated with the "@Service" annotation.
  • Entity Layer: All classes that map to the real world are contained in this layer. Usually all ORM related annotations are placed in these classes. — If it connects with MySQL, we annotate the table name with "@Entity". — If it's connected to MongoDB, we annotate the collection name with "@Document".

Also, we can define getters and setters here using a library like Lombok.

9. How to use Spring Boot to connect to the database?

Usually we don't need to create singleton database class, connection pool method and any other implementation. Spring Boot Auto Configuration will do all these classes and configuration setup for us. Just need to set.

  1. Add starter dependencies for databases (MySQL/MongoDB/Redis) to the POM.
  2. Define configuration in application.properties/yml file - eg: database URL and credentials

10. How to write custom query in DAO layer?

Usually at the Repository layer, we extend the interface with the JPARepository or MongoRepository interface. Afterwards, our Repository (DAO) will have all the methods available in the Spring Boot Repository interface. Es: save(), saveAll(), findById(), find(), etc.

But depending on our business needs, we may need some other methods.

Ex: findByEmail(), findUsersByRegion() etc... singleton

So we have to provide custom query in this case. We have "@Query" annotation to achieve this. Just define the query before each method definition. that's all!

If we use JPA, we have to create queries using JPQL (Java Persistence Query Language). It is defined in the JPA specification and is an object-oriented query language for performing database operations on persistent entities.

Example: Find only users in a given area

@Query(<font>"select u from users u where u.region =: region"</font><font>) 
Optional<List<User>> findUsersByRegion(String region);
</font>

11. How to handle transactions in Spring Boot? Any annotations used?

Spring Boot provides an annotation called "@Transactional" to manage transactions.

Let's assume a product ordering scenario. We need to process the order in the Order Service and send the payment details to the Payment Service through a REST call. Imagine that a payment service suddenly stops. If you save the order details in your own database before sending the API call to the payment service, there will be discrepancies in the future because the payment service data is losing that record!

To avoid this, we can put the "@Transactional" annotation into the method of the order service. Then from there, if there is a failure calling the payment service, all data in the ongoing process will be rolled back!

@Transactional
 <b>public</b> Order orderProduct(Product product, Double payment) { 
    <font><i>// 处理订单</i></font><font>
    </font><font><i>// 向支付服务发送 REST 调用</i></font><font>
}
</font>

12. Where do we need to use the "@Qualifier" annotation?

This annotation is used to specifically tell Spring Boot to fetch a particular class from all its available implementing beans. The @Qualifier annotation is used together with the "@Autowired" annotation for dependency injection.

Suppose we have 1 interface and 2 different implementing classes.

For example: UserService interface => AdminUserService, StaffUserService class

Both AdminUserService and StaffUserService are implementing the UserService interface. We have to select StaffUserService at service startup. Otherwise Spring Boot will throw an exception and complain about too many candidates.

See the error below...

Description:
Field userService in com.example.demo.UserExecutor required a single bean, but 2 were found:
 - adminUserService: defined in file [/home/salitha/Downloads/demo/target/<b>class</b>es/com/example/demo/AdminUserService.<b>class</b>]
 - staffUserService: defined in file [/home/salitha/Downloads/demo/target/<b>class</b>es/com/example/demo/StaffUserService.<b>class</b>]
Action:
Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

So we should put Qualifier annotation after Autowired to solve this problem:

@Autowired 
@Qualifier(<font>"staffUserService"</font><font>) 
<b>private</b> UserService userService;
</font>

Example Java class setup to test this:

<b>import</b> org.springframework.beans.factory.annotation.Autowired;
<b>import</b> org.springframework.beans.factory.annotation.Qualifier;
<b>import</b> org.springframework.boot.SpringApplication;
<b>import</b> org.springframework.boot.autoconfigure.SpringBootApplication;
<b>import</b> org.springframework.context.annotation.AnnotationConfigApplicationContext;
<b>import</b> org.springframework.context.annotation.ComponentScan;
<b>import</b> org.springframework.context.annotation.Configuration;
<b>import</b> org.springframework.stereotype.Component;
<b>import</b> org.springframework.stereotype.Service;

<b>import</b> javax.annotation.PostConstruct;

@SpringBootApplication
<b>public</b> <b>class</b> DemoApplication {
   <b>public</b> <b>static</b> <b>void</b> main(String args) {
      SpringApplication.run(DemoApplication.<b>class</b>, args);
   }
}

<b>interface</b> UserService {
   <b>void</b> login();
}

@Service
<b>class</b> AdminUserService implements UserService {
   @Override
   <b>public</b> <b>void</b> login() {
      System.out.println(<font>"Admin Login"</font><font>);
   }
}

@Service
<b>class</b> StaffUserService  implements UserService {
   @Override
   <b>public</b> <b>void</b> login() {
      System.out.println(</font><font>"Staff Login"</font><font>);
   }
}

@Configuration
@ComponentScan(</font><font>"com.example.demo"</font><font>)
<b>class</b> AppConfig {
   @Autowired
   UserExecutor userExecutor;

   @PostConstruct
   <b>void</b> testBeans() {
      userExecutor.getLogin();
   }
}

@Component
<b>class</b> UserExecutor {
   @Autowired
   @Qualifier(</font><font>"staffUserService"</font><font>)
   <b>private</b> UserService userService;
   <b>public</b> <b>void</b> getLogin() {
      userService.login();
   }
}
</font>

13. Can Tomcat server be replaced in Spring Boot project?

Yes. We can remove Tomcat server if needed by adding maven exclusion in POM. In fact, the web server is bundled in the started-web Spring Boot starter dependency. Exclusions should be added.

<dependency> 
  <groupId>org.springframework.boot</groupId> 
  <artifactId>spring-boot-starter-web</artifactId> 
  <exclusions> 
    <exclusion> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId> spring-boot-starter-tomcat</artifactId> 
    </exclusion> 
  </exclusions> 
</dependency>

Then we have to add any other servers (like Jetty) to the POM. Anyway, we have to add a web server after removing tomcat.

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

You will now see Jetty server logs instead of Tomcat.

2022-08-03 13:22:12.551 INFO 57495 --- [main] osbweb.embedded.jetty.JettyWebServer:Jetty 在端口 8080 (http/1.1) 上启动,上下文路径为“/”

14. What is the difference between "@PathVariable" and "@RequestParam"?

PathVariable - Use "/" separated parameters when we set the API endpoint.

@GetMapping(path = <font>"/profile/{username}"</font><font>) 
<b>public</b> ResponseEntity<?> getUser( @PathVariable(</font><font>"username"</font><font>) String username) { 
    <b>return</b> ResponseEntity.ok().body(authService.findUserByUsername(username)); 
}
</font>

API 端点:
http://localhost/api/profile/salitha

RequestParam - Used when we set up the API endpoint, the query parameters are separated by "&" and start with "?".

@GetMapping(path = <font>"/confirm"</font><font>) 
<b>public</b> ResponseEntity<?> confirmUser( @RequestParam(</font><font>"token"</font><font>) String token) { 
    <b>return</b> ResponseEntity. ok ().body(authService.confirmUser(token)); 
}
</font>

API 端点:
http://localhost/api/profile?token=12345678

15. What is the use of "@Primary" annotation?

@Primary indicates that a bean should be given priority when multiple candidates are eligible to autowire a single-valued dependency.

17. How to validate incoming requests and notify users of errors?

There are several main steps that need to be performed for this. If we follow these, it's just a matter of validating the request.

  1. We have added the enabler validation dependency to the POM.
<dependency> 
   <groupId>org.springframework.boot</groupId> 
   <artifactId>spring-boot-starter-validation</artifactId> 
</dependency>

2. Add the "@Valid" annotation before the "RequestBody" annotation.

3. Create a separate DTO for the request to display validation constraint messages.

4. Create a global exception handler using "@RestControllerAdvice" and handle MethodArgumentNotValidException in a separate method
.

5. Create logic to return errors to end users as needed. We can extract the exception message in this logic.es

18. What is Spring Boot Actuator?

Simply put, a subproject of the Spring Boot framework that uses HTTP endpoints to expose operational information about any running application.

This information includes application metrics, connected database state, application state, bean information, request traces, and more.

It is available as a starter dependency. We can use this library by installing the following dependencies.

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

19. How to deal with exceptions in Spring Boot microservices?

We can do this in a centralized manner. We need a global configuration class to predefine exception handling methods for each exception class. We can also use the handler itself to define the returned HTTP status code.

  • Create a global exception handler using "@RestControllerAdvice" and handle each exception in a separate method.
  • Create logic to return errors to end users as needed. We can extract the exception message in this logic
@RestControllerAdvice
<b>public</b> <b>class</b> GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.<b>class</b>)
    <b>public</b> ResponseEntity<Map<String, List<String>>> handleValidationErrors(MethodArgumentNotValidException ex) {
        List<String> errors = ex.getBindingResult().getFieldErrors()
                .stream().map(FieldError::getDefaultMessage).collect(Collectors.toList());
        <b>return</b> <b>new</b> ResponseEntity<>(getErrorsMap(errors), <b>new</b> HttpHeaders(), HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(UserNotFoundException.<b>class</b>)
    <b>public</b> ResponseEntity<Map<String, List<String>>> handleNotFoundException(UserNotFoundException ex) {
        List<String> errors = Collections.singletonList(ex.getMessage());
        <b>return</b> <b>new</b> ResponseEntity<>(getErrorsMap(errors), <b>new</b> HttpHeaders(), HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(Exception.<b>class</b>)
    <b>public</b> <b>final</b> ResponseEntity<Map<String, List<String>>> handleGeneralExceptions(Exception ex) {
        List<String> errors = Collections.singletonList(ex.getMessage());
        <b>return</b> <b>new</b> ResponseEntity<>(getErrorsMap(errors), <b>new</b> HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(RuntimeException.<b>class</b>)
    <b>public</b> <b>final</b> ResponseEntity<Map<String, List<String>>> handleRuntimeExceptions(RuntimeException ex) {
        List<String> errors = Collections.singletonList(ex.getMessage());
        <b>return</b> <b>new</b> ResponseEntity<>(getErrorsMap(errors), <b>new</b> HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    <b>private</b> Map<String, List<String>> getErrorsMap(List<String> errors) {
        Map<String, List<String>> errorResponse = <b>new</b> HashMap<>();
        errorResponse.put(<font>"errors"</font><font>, errors);
        <b>return</b> errorResponse;
    }

}
</font>

20. What is the difference between "@Entity" and "@Table" annotations?

Entities represent the classes you will use in your program, and tables represent the actual database tables you will access through your program.

The above are the most comprehensive questions that will be asked in more than 90% of the interviews. If you need a full version of the PDF file, you can [ click ]

Guess you like

Origin blog.csdn.net/xxxzzzqqq_/article/details/129926457