The architect will take you for an interview ①Spring Boot interview questions

A summary of the Java interview, including basic Java knowledge, collection containers, concurrent programming, JVM, commonly used open source framework Spring, MyBatis, database, middleware, etc., including what you need or may use in the interview as a Java engineer Most knowledge. Everyone is welcome to read. I have limited knowledge, and there are inevitably mistakes or omissions in the blog I wrote. I hope you guys can give me advice. I am grateful. The article is continuously updated...

Article Directory

Overview
1. What is Spring Boot?
2. What are the advantages of Spring Boot?
3. What is the core annotation of Spring Boot? Which annotations are mainly composed of?
Configuration
4. What is JavaConfig?
5. What is the principle of Spring Boot automatic configuration?
6. How do you understand the Spring Boot configuration loading sequence?
7. What is YAML?
8. What are the advantages of YAML configuration?
9. Can Spring Boot use XML configuration?
10. What is the core configuration file of spring boot? What is the difference between bootstrap.properties and application.properties?
11. What is Spring Profiles?
12. How to run Spring Boot applications on custom ports?
Security
13. How to realize the security of Spring Boot application?
14. Compare the advantages and disadvantages of Spring Security and Shiro?
15. How to solve the cross-domain problem in Spring Boot?
16. What is a CSRF attack?
Monitor
17. What is the monitor in Spring Boot?
18. How to disable Actuator endpoint security in Spring Boot?
19. How do we monitor all Spring Boot microservices?
Integration of third-party projects
20. What is WebSockets?
21. What is Spring Data?
22. What is Spring Batch?
23. What is a FreeMarker template?
24. How to integrate Spring Boot and ActiveMQ?
25. What is Apache Kafka?
26. What is Swagger? Have you implemented it with Spring Boot?
27. The front and back ends are separated, how to maintain the interface document?
Other
28. How to reload the changes on Spring Boot without restarting the server? 29. How to hot deploy the Spring Boot project?
30. What starter maven dependencies did you use?
31. What is the starter in Spring Boot?
32. What is the use of spring-boot-starter-parent?
33. What is the difference between a
Spring Boot jar and an ordinary jar? 34. What are the ways to run Spring Boot ?
35. Does Spring Boot need a separate container to run?
36. What are the ways to enable Spring Boot features?
37. How to use Spring Boot to implement exception handling?
38. How to use Spring Boot to realize paging and sorting?
39. How to implement session sharing in
microservices ? 40. How to implement timing tasks in Spring Boot?

Overview

What is Spring Boot?

Spring Boot is a sub-project under the Spring open source organization. It is a one-stop solution for Spring components. It mainly simplifies the difficulty of using Spring, saves heavy configuration, provides various starters, and developers can quickly get started.

What are the advantages of Spring Boot?

Spring Boot has the following advantages:

Easy to use, improve development efficiency, and provide a faster and more extensive introductory experience for Spring development.
Out of the box, away from cumbersome configuration.
Provides a series of non-business functions common to large-scale projects, such as: embedded server, security management, operation data monitoring, operation status check and external configuration, etc.
There is no code generation, and no XML configuration is required.
Avoid a large number of Maven imports and various version conflicts.
What is the core annotation of Spring Boot? Which annotations are mainly composed of?

The annotation above the startup class is @SpringBootApplication, which is also the core annotation of Spring Boot. The main combination includes the following 3 annotations:

@SpringBootConfiguration: Combines the @Configuration annotations to realize the function of the configuration file.

@EnableAutoConfiguration: Turn on the automatic configuration function, you can also turn off a certain automatic configuration option, such as turning off the data source automatic configuration function: @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class }).

@ComponentScan: Spring component scanning.

Configuration

What is JavaConfig?

Spring JavaConfig is a product of the Spring community. It provides a pure Java method for configuring the Spring IoC container. So it helps to avoid the use of XML configuration. The advantages of using JavaConfig are:

(1) Object-oriented configuration. Since configuration is defined as a class in JavaConfig, users can take full advantage of the object-oriented features in Java. One configuration class can inherit another, override its @Bean method, etc.

(2) Reduce or eliminate XML configuration. The benefits of externalized configuration based on the principle of dependency injection have been proven. However, many developers do not want to switch back and forth between XML and Java. JavaConfig provides developers with a pure Java method to configure the Spring container similar to the XML configuration concept. From a technical point of view, it is feasible to use only the JavaConfig configuration class to configure the container, but in fact, many people think that mixing and matching JavaConfig with XML is ideal.

(3) Type safety and refactoring friendly. JavaConfig provides a type-safe way to configure the Spring container. Thanks to Java 5.0's support for generics, beans can now be retrieved by type instead of name, without any casting or string-based lookup.

What is the principle of Spring Boot automatic configuration?

The annotation @EnableAutoConfiguration, @Configuration, @ConditionalOnClass is the core of automatic configuration,

@EnableAutoConfiguration imports the automatic configuration class defined in META-INF/spring.factories to the container.

Filter valid auto-configuration classes.

Each automatic configuration class combines the corresponding xxxProperties.java to read the configuration file for automatic configuration function

How do you understand the Spring Boot configuration loading sequence?

In Spring Boot, there are several ways to load configuration.

1) properties file;

2) YAML file;

3) System environment variables;

4) Command line parameters;

and many more……

What is YAML?

YAML is a human-readable data serialization language. It is usually used for configuration files. Compared with the property file, if we want to add complex properties to the configuration file, the YAML file is more structured and less confusing. It can be seen that YAML has hierarchical configuration data.

What are the advantages of YAML configuration?

YAML can now be regarded as a very popular configuration file format. You can see YAML configuration no matter whether it is front-end or back-end. So what are the advantages of YAML configuration compared to traditional properties configuration?

Orderly configuration. In some special scenarios, orderly configuration is critical.
Support arrays. The elements in the array can be basic data types or objects.
Concise.
Compared with properties configuration files, YAML has another disadvantage, that is, it does not support @PropertySource. Import custom YAML configuration.

Can Spring Boot use XML configuration?

Spring Boot recommends using Java configuration instead of XML configuration, but XML configuration can also be used in Spring Boot. An XML configuration can be introduced through the @ImportResource annotation.

What is the spring boot core configuration file? What is the difference between bootstrap.properties and application.properties?

Simply doing Spring Boot development may not be easy to encounter the bootstrap.properties configuration file, but when combined with Spring Cloud, this configuration will often be encountered, especially when you need to load some remote configuration files.

Two configuration files of spring boot core:

bootstrap (. yml or. properties): boostrap is loaded by the parent ApplicationContext, which is loaded prior to applicaton, and the configuration takes effect in the boot phase of the application context. Generally speaking, we will use it in Spring Cloud Config or Nacos. And the properties in boostrap cannot be overwritten;
application (. yml or. Properties): loaded by ApplicatonContext and used for automatic configuration of spring boot projects.
What is Spring Profiles?

Spring Profiles allows users to register beans based on configuration files (dev, test, prod, etc.). Therefore, when the application is running in development, only certain beans can be loaded, while in PRODUCTION, certain other beans can be loaded. Suppose our requirement is that the Swagger document is only applicable to the QA environment, and all other documents are disabled. This can be done using configuration files. Spring Boot makes it very easy to use configuration files.

How to run Spring Boot applications on custom ports?

In order to run Spring Boot applications on a custom port, you can specify the port in application.properties. server.port = 8090

Safety

How to realize the security of Spring Boot application?

In order to achieve the security of Spring Boot, we use the spring-boot-starter-security dependency, and security configuration must be added. It requires very little code. The configuration class will have to extend WebSecurityConfigurerAdapter and override its methods.

Compare the advantages and disadvantages of Spring Security and Shiro?

Since Spring Boot officially provides a large number of very convenient out-of-the-box Starters, including Spring Security's Starter, it makes it easier to use Spring Security in Spring Boot, and even only need to add a dependency to protect all interfaces. Therefore, if it is a Spring Boot project, Spring Security is generally chosen. Of course, this is only a suggested combination. From a purely technical point of view, no matter how the combination is, there is no problem. Compared with Spring Security, Shiro has the following characteristics:

Spring Security is a heavyweight security management framework; Shiro is a lightweight security management framework
Spring Security concept complex, cumbersome configuration; Shiro simple in concept, simple to configure
Spring Security is powerful; Shiro features a simple
Spring Boot How to resolve cross Domain issue?

Cross-domain can be solved through JSONP at the front end, but JSONP can only send GET requests and cannot send other types of requests. In RESTful style applications, it is very tasteless, so we recommend passing (CORS, Cross-origin) on the back end. resource sharing) to solve cross-domain problems. This solution is not unique to Spring Boot. In the traditional SSM framework, CORS can be used to solve cross-domain problems, but before we configured CORS in an XML file, we can now implement the WebMvcConfigurer interface and then rewrite the addCorsMappings method Solve cross-domain issues.

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    
    
    @Override
    public void addCorsMappings(CorsRegistry registry) {
    
    
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .maxAge(3600);
    }
}

The front and back ends of the project are deployed separately, so cross-domain issues need to be solved.
We use cookies to store the user's login information, and perform permission control in the spring interceptor. When the permissions do not match, the fixed json result is directly returned to the user.
After the user logs in, it is used normally; when the user logs out of the login state or the token expires, due to the problem of the interceptor and the cross-domain sequence, a cross-domain phenomenon occurs.
We know that for an http request, the filter is passed first, and then the interceptor is processed after it reaches the servlet. If we put cors in the filter, it can be executed prior to the permission interceptor.

@Configuration
public class CorsConfig {
    
    
    @Bean
    public CorsFilter corsFilter() {
    
    
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}

What is a CSRF attack?

CSRF stands for cross-site request forgery. This is an attack that forces the end user to perform unwanted actions on the currently authenticated web application. CSRF attacks specifically target state change requests, not data theft, because the attacker cannot view the response to the forged request.

Monitor

What is the monitor in Spring Boot?

Spring boot actuator is one of the important functions in the spring boot framework. The Spring boot monitor helps you access the current state of the running application in the production environment. There are several indicators that must be checked and monitored in the production environment. Even some external applications may be using these services to trigger alert messages to relevant personnel. The monitor module exposes a set of REST endpoints that can be directly accessed as HTTP URLs to check the status.

How to disable Actuator endpoint security in Spring Boot?

By default, all sensitive HTTP endpoints are secure, and only users with the ACTUATOR role can access them. Security is implemented using the standard HttpServletRequest.isUserInRole method. We can use to disable security. It is only recommended to disable security when the actuator endpoint is accessed behind a firewall.

How do we monitor all Spring Boot microservices?

Spring Boot provides monitor endpoints to monitor the metrics of each microservice. These endpoints are useful for obtaining information about applications (such as whether they have been started) and whether their components (such as databases, etc.) are functioning properly. However, one of the main disadvantages or difficulties of using the monitor is that we must open the knowledge points of the application separately to understand its status or health. Imagine a microservice involving 50 applications. The administrator will have to hit the execution terminals of all 50 applications. To help us deal with this situation, we will use the open source project located at. It is built on Spring Boot Actuator, which provides a Web UI that allows us to visualize the metrics of multiple applications.

Integrate third-party projects

What is WebSockets?

WebSocket is a computer communication protocol that provides a full-duplex communication channel through a single TCP connection.

1. WebSocket is bidirectional-use WebSocket client or server to initiate message sending.

2. WebSocket is full duplex-client and server communication are independent of each other.

3. Single TCP connection-the initial connection uses HTTP, and then this connection is upgraded to a socket-based connection. Then this single connection is used for all future communications

4. Light-Compared with http, WebSocket message data exchange is much lighter.

What is Spring Data?

Spring Data is a sub-project of Spring. Used to simplify database access, supporting NoSQL and relational data storage. Its main goal is to make database access convenient and fast. Spring Data has the following characteristics:

The SpringData project supports NoSQL storage:

MongoDB (document database)
Neo4j (graph database)
Redis (key/value storage
)
Hbase (column family database) Relational data storage technologies supported by the SpringData project:

JDBC
JPA
Spring Data Jpa is committed to reducing the amount of data access layer (DAO) development. The only thing developers have to do is to declare the interface of the persistence layer, and Spring Data JPA will do the rest for you! Spring Data JPA determines what kind of logic the method needs to implement according to the name of the standard method according to the name of the standard.

What is Spring Batch?

Spring Boot Batch provides reusable functions, these functions are very important when processing a large number of records, including log/tracing, transaction management, job processing statistics, job restart, skip and resource management. It also provides more advanced technical services and functions. Through optimization and partitioning technology, extremely high batch and high-performance batch processing jobs can be realized. Simple and complex large batch processing jobs can use the framework to process important and large amounts of information in a highly scalable manner.

What is a FreeMarker template?

FreeMarker is a Java-based template engine that initially focused on the use of MVC software architecture for dynamic web page generation. The main advantage of using Freemarker is the complete separation of the presentation layer and the business layer. The programmer can handle the application code, and the designer can handle the html page design. Finally, use freemarker to combine these to give the final output page.

How to integrate Spring Boot and ActiveMQ?

For integrating Spring Boot and ActiveMQ, we use dependencies. It requires very little configuration and no boilerplate code.

What is Apache Kafka?

Apache Kafka is a distributed publish-subscribe messaging system. It is a scalable, fault-tolerant publish-subscribe messaging system, which enables us to build distributed applications. This is an Apache top-level project. Kafka is suitable for offline and online message consumption.

What is Swagger? Have you implemented it with Spring Boot?

Swagger is widely used to visualize APIs, using Swagger UI to provide online sandboxes for front-end developers. Swagger is a tool for generating visual representations of RESTful Web services, specification and complete framework implementation. It enables documents to be updated at the same speed as the server. When correctly defined through Swagger, consumers can use the least amount of implementation logic to understand and interact with remote services. Therefore, Swagger eliminates guesswork when calling services.

The front and back ends are separated, how to maintain interface documents?

Front-end and back-end development is becoming more and more popular. In most cases, we use Spring Boot to do front-end and back-end development. There must be interface documents for front-end and back-end separation, otherwise the front and back ends will be deeply involved in wrangling. A more stupid way is to use word or md to maintain interface documents, but the efficiency is too low. When the interface changes, the documents in everyone's hands have to change. In Spring Boot, the common solution to this problem is Swagger. Using Swagger we can quickly generate an interface documentation website. Once the interface changes, the documentation will be automatically updated. All development engineers can access this online website to get the latest Interface documentation is very convenient.

other

How to reload changes on Spring Boot without restarting the server? How to hot deploy Spring Boot project?

This can be achieved using the DEV tool. With this dependency, you can save any changes and the embedded tomcat will restart. Spring Boot has a development tools (DevTools) module, which helps improve the productivity of developers. One of the main challenges facing Java developers is to automatically deploy file changes to the server and automatically restart the server. Developers can reload changes on Spring Boot without restarting the server. This will eliminate the need to manually deploy changes each time. Spring Boot did not have this feature when it released its first version. This is the most requested feature for developers. The DevTools module fully meets the needs of developers. This module will be disabled in the production environment. It also provides an H2 database console to better test applications.

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

Which starter maven dependencies did you use?

Some of the following dependencies are used

spring-boot-starter-activemq

spring-boot-starter-security

This helps to increase fewer dependencies and reduce version conflicts.

What is the starter in Spring Boot?

First of all, this Starter is not a new technical point, and is basically implemented based on the existing functions of Spring. First of all, it provides an automated configuration class, generally named XXXAutoConfiguration. In this configuration class, conditional annotations are used to determine whether a configuration takes effect (conditional annotations are inherent in Spring), and then it also provides a series of default configurations , Developers are also allowed to customize the relevant configuration according to the actual situation, and then inject these configuration attributes through type-safe attribute injection, and the newly injected attributes will replace the default attributes. Because of this, many third-party frameworks can be used directly by introducing dependencies. Of course, developers can also customize Starter

What is the use of spring-boot-starter-parent?

We all know that a newly created Spring Boot project has a parent by default. This parent is spring-boot-starter-parent. Spring-boot-starter-parent mainly has the following functions:

The Java compiled version is defined as 1.8.
Use UTF-8 format encoding.
Inherited from spring-boot-dependencies, this defines the version of the dependency. It is precisely because this dependency is inherited that we do not need to write the version number when writing the dependency.
The configuration to perform the packaging operation.
Automated resource filtering.
Automated plug-in configuration.
Resource filtering for application.properties and application.yml, including configuration files of different environments defined by the profile, such as application-dev.properties and application-dev.yml.
What is the difference between Spring Boot's jar and ordinary jar?

The jar finally packaged into the Spring Boot project is an executable jar. This jar can be run directly through the java -jar xxx.jar command. This jar cannot be used as an ordinary jar by other projects. Even if it depends, it cannot be used. the type.

Spring Boot's jar cannot be relied on by other projects, mainly because its structure is different from ordinary jars. Ordinary jar package, the package name is directly after decompression, and our code is in the package. After the executable jar packaged by Spring Boot is decompressed, it is our code in the \BOOT-INF\classes directory, so it cannot be directly Reference. If you have to refer to it, you can add configuration to the pom.xml file and package the Spring Boot project into two jars, one executable and one referenceable.

What are the ways to run Spring Boot?

1) Command for packaging or run in a container

2) Run with Maven/Gradle plugin

3) Directly execute the main method to run

Does Spring Boot need a separate container to run?

No need, built-in containers such as Tomcat/ Jetty.

What are the ways to enable Spring Boot features?

1) Inherit the spring-boot-starter-parent project

2) Import spring-boot-dependencies project dependencies

How to use Spring Boot to implement exception handling?

Spring provides a very useful way to use ControllerAdvice to handle exceptions. We implement a ControlerAdvice class to handle all exceptions thrown by the controller class.

How to use Spring Boot to implement paging and sorting?

Using Spring Boot to implement paging is very simple. Use Spring Data-JPA to pass pageable to the repository method.

How to realize session sharing in microservices?

In microservices, a complete project is split into multiple different independent services, each service is independently deployed on different servers, and their respective sessions are separated from the physical space, but often, we need to Sharing sessions between different microservices, a common solution is Spring Session + Redis to achieve session sharing. The sessions of all microservices are stored uniformly on Redis. When each microservice has related read and write operations on the session, all the sessions on Redis are operated. In this way, session sharing is realized. Spring Session is implemented based on the proxy filter in Spring, making the synchronization operation of the session transparent to developers and very simple.

How to implement timing tasks in Spring Boot?

Timing tasks are also a common requirement. The support for timing tasks in Spring Boot mainly comes from the Spring framework.

There are two different ways to use timed tasks in Spring Boot, one is to use the @Scheduled annotation in Spring, and the other is to use the third-party framework Quartz.

The way to use @Scheduled in Spring is mainly achieved through the @Scheduled annotation.

To use Quartz, you can define Job and Trigger in the same way as Quartz.

My public account: Muzi Network Sideline, welcome to pay attention and exchange!

Guess you like

Origin blog.csdn.net/ncw8080/article/details/113877812