One day to understand SpringBoot interview stereotyped essay

Advantages of Spring Boot

  • The built-in servlet container does not need to deploy tomcat on the server. You only need to package the project into a jar package, and use java -jar xxx.jar to start the project with one click
  • SpringBoot provides a starter, which aggregates commonly used libraries, simplifies complex environment configurations, and quickly builds a spring application environment
  • Can quickly create a spring project that runs independently and integrates mainstream frameworks
  • Running application monitoring in quasi-production environment

What exactly is the starter in SpringBoot?

The starter provides an automatic configuration class, generally named XXXAutoConfiguration, in which conditional annotations are used to determine whether a configuration takes effect (conditional annotations are originally in Spring), and then it also provides a series of default configurations, It also allows developers to customize relevant configurations according to the actual situation, and then inject these configuration properties through type-safe property injection, and the newly injected properties will replace the default properties. Because of this, we can use many third-party frameworks directly only by introducing dependencies.

What are the ways to run SpringBoot?

  1. Package with commands or run in a container
  2. Run with Maven/Gradle plugin
  3. Directly execute the main method to run

This article has been included in the Github warehouse, which includes computer foundation, Java foundation, multithreading, JVM, database, Redis, Spring, Mybatis, SpringMVC, SpringBoot, distributed, microservices, design patterns, architecture, school recruitment and social recruitment sharing, etc. Core knowledge points, welcome to star~

Github address

If you can't access Github, you can access the gitee address.

gitee address

What are the starters commonly used by SpringBoot?

  1. spring-boot-starter-web: provides Spring MVC + embedded Tomcat.
  2. spring-boot-starter-data-jpa : Provides Spring JPA + Hibernate.
  3. spring-boot-starter-data-Redis : Provides Redis.
  4. mybatis-spring-boot-starter : Provided by MyBatis.

Which is the core annotation of Spring Boot?

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

  • @SpringBootConfiguration: The @Configuration annotation is combined to realize the function of the configuration file.

  • @EnableAutoConfiguration: Turn on the automatic configuration function, or turn off an automatic configuration option, such as turning off the data source automatic configuration function: @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }).

  • @ComponentScan: Spring component scan.

Principle of automatic configuration

Diagram of SpringBoot's automatic configuration principle:

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-COd4ugEU-1682819595806) (http://img.topjavaer.cn/img/SpringBoot’s automatic configuration principle.jpg )]

Set the property debug=true in application.properties, you can view the enabled and disabled automatic configuration in the console.

@SpringBootApplication is a combination of @Configuration, @EnableAutoConfiguration and @ComponentScan.

@Configuration indicates that the class is a Java configuration class.

@ComponentScan enables automatic scanning of eligible beans (annotations such as @Controller, @Service, etc. are added).

@EnableAutoConfiguration will automatically configure the project according to the jar dependencies in the class path. For example, if dependencies are added spring-boot-starter-web, the dependencies of Tomcat and Spring MVC will be automatically added, and then Spring Boot will automatically configure Tomcat and Spring MVC (spring.factories EnableAutoConfiguration configuration WebMvcAutoConfiguration).

Let me share with you a Github warehouse, which contains more than 300 classic computer book PDFs compiled by Dabin, including C language, C++, Java, Python, front-end, database, operating system, computer network, data structure and algorithm, machine learning, Programming life , etc., you can star it, next time you look for a book directly search on it, the warehouse is continuously updated~

Github address

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
    
    
}

EnableAutoConfiguration is mainly composed of two annotations @AutoConfigurationPackage and @Import(EnableAutoConfigurationImportSelector.class).

@AutoConfigurationPackage is used to register all components in the package where the startup class is located to the spring container.

@Import injects EnableAutoConfigurationImportSelector into the spring container. EnableAutoConfigurationImportSelector reads the META-INF/spring.factories file information from the class path through SpringFactoriesLoader. There is a key in this file for org.springframework.boot.autoconfigure.EnableAutoConfiguration, which defines a set of The bean that needs to be autoconfigured.

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\

Not all of these configuration classes will be loaded. It will be judged whether to load according to conditions such as @ConditionalOnClass on xxxAutoConfiguration. Only when the conditions are met will the corresponding components be loaded into the spring container. (For example, mybatis-spring-boot-starter will automatically configure the components required by mybatis such as sqlSessionFactory, sqlSessionTemplate, and dataSource)

@Configuration
@ConditionalOnClass({
    
     EnableAspectJAutoProxy.class, Aspect.class, Advice.class,
		AnnotatedElement.class }) //类路径存在EnableAspectJAutoProxy等类文件,才会加载此配置类
@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", matchIfMissing = true)
public class AopAutoConfiguration {
    
    

	@Configuration
	@EnableAspectJAutoProxy(proxyTargetClass = false)
	@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false", matchIfMissing = false)
	public static class JdkDynamicAutoProxyConfiguration {
    
    

	}

	@Configuration
	@EnableAspectJAutoProxy(proxyTargetClass = true)
	@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true", matchIfMissing = true)
	public static class CglibAutoProxyConfiguration {
    
    

	}

}

How does the attribute in the global configuration file take effect, for example: how does server.port=8081 take effect?

The role of @ConfigurationProperties is to bind the properties of the configuration file to the corresponding beans. Global configuration properties such as: server.port, etc., are bound to the corresponding XxxxProperties bean through the @ConfigurationProperties annotation, and the corresponding properties (serverProperties.getPort()) are obtained through this bean.

//server.port = 8080
@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true)
public class ServerProperties {
    
    
	private Integer port;
	private InetAddress address;

	@NestedConfigurationProperty
	private final ErrorProperties error = new ErrorProperties();
	private Boolean useForwardHeaders;
	private String serverHeader;
    //...
}

Implement automatic configuration

Realize that when a certain class exists, the bean of this class is automatically configured, and the properties of the bean can be configured in application.properties.

(1) Create a new Maven project spring-boot-starter-hello, modify pom.xml as follows:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.tyson</groupId>
    <artifactId>spring-boot-starter-hello</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>1.3.0.M1</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
        </dependency>
    </dependencies>

</project>

(2) Attribute configuration

public class HelloService {
    
    
    private String msg;

    public String getMsg() {
    
    
        return msg;
    }

    public void setMsg(String msg) {
    
    
        this.msg = msg;
    }

    public String sayHello() {
    
    
        return "hello" + msg;

    }
}


import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix="hello")
public class HelloServiceProperties {
    
    
    private static final String MSG = "world";
    private String msg = MSG;

    public String getMsg() {
    
    
        return msg;
    }

    public void setMsg(String msg) {
    
    
        this.msg = msg;
    }
}

(3) Automatic configuration class

import com.tyson.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(HelloServiceProperties.class) //1
@ConditionalOnClass(HelloService.class) //2
@ConditionalOnProperty(prefix="hello", value = "enabled", matchIfMissing = true) //3
public class HelloServiceAutoConfiguration {
    
    

    @Autowired
    private HelloServiceProperties helloServiceProperties;

    @Bean
    @ConditionalOnMissingBean(HelloService.class) //4
    public HelloService helloService() {
    
    
        HelloService helloService = new HelloService();
        helloService.setMsg(helloServiceProperties.getMsg());
        return helloService;
    }
}
  1. The @EnableConfigurationProperties annotation enables property injection, and injects classes annotated with @ConfigurationProperties as beans of the Spring container.

  2. When HelloService is in the condition of the classpath.

  3. When hello=enabled is set, if it is not set, it defaults to true, that is, the condition is met.

  4. When the container does not have this bean.

(4) Registration configuration

For automatic configuration to take effect, you need to register the automatic configuration class. Create a new META-INF/spring.factories under src/main/resources. Add the following:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.tyson.config.HelloServiceAutoConfiguration

"\" is to still read the attribute after the newline. If there are multiple automatic configurations, separate them with commas.

(5) Use the starter

Add in the pom.xml of the Spring Boot project:

<dependency>
    <groupId>com.tyson</groupId>
    <artifactId>spring-boot-starter-hello</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

The running class is as follows:

import com.tyson.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class SpringbootDemoApplication {
    
    

    @Autowired
    public HelloService helloService;

    @RequestMapping("/")
    public String index() {
    
    
        return helloService.getMsg();
    }

    public static void main(String[] args) {
    
    
        SpringApplication.run(SpringbootDemoApplication.class, args);
    }

}

There is no HelloService bean configured in the project, but we can inject this bean, which is achieved through auto-configuration.

Add the debug property in application.properties, run the configuration class, and you can see in the console:

   HelloServiceAutoConfiguration matched:
      - @ConditionalOnClass found required class 'com.tyson.service.HelloService' (OnClassCondition)
      - @ConditionalOnProperty (hello.enabled) matched (OnPropertyCondition)

   HelloServiceAutoConfiguration#helloService matched:
      - @ConditionalOnMissingBean (types: com.tyson.service.HelloService; SearchStrategy: all) did not find any beans (OnBeanCondition)

The content of msg can be configured in application.properties:

hello.msg=大彬

The principle of @Value annotation

The resolution of @Value is in the bean initialization phase. BeanPostProcessor defines the interface method that the user can operate on the bean before and after the bean is initialized. One of its important implementation classes AutowiredAnnotationBeanPostProcessorprovides support for the injection function of the @Autowired and @Value annotations in the bean.

Does Spring Boot need a standalone container to run?

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

What logging frameworks does Spring Boot support?

Spring Boot supports Java Util Logging, Log4j2, and Lockback as log frameworks. If you use the Starters starter, Spring Boot will use Logback as the default log framework, but no matter what kind of log framework it supports outputting configuration files to the console or files middle.

What are the advantages of YAML configuration?

Compared with traditional properties configuration, YAML configuration has these advantages:

  • Orderly configuration
  • Concise and clear, supports arrays, elements in arrays can be basic data types or objects

The disadvantage is that it does not support @PropertySource annotation to import custom YAML configuration.

What are Spring Profiles?

In the development of the project, some configuration files may be different in different environments such as development, testing or production, such as database connection, redis configuration, etc. So how do we automatically switch between configurations in different environments? Spring provides us with the profiles mechanism to provide us with the function of switching configuration files back and forth

Spring Profiles allow users to register beans according to configuration files (dev, test, prod, etc.). So when the application is running in development only certain beans can be loaded and in PRODUCTION some other beans can be loaded. Let's say our requirement is that Swagger documentation is only available in the QA environment and all other documentation is disabled. This can be done using configuration files. Spring Boot makes using configuration files very simple.

How to manage SpringBoot multi-data source transactions

The first way is to use transactionManager in @TransactionManager of the service layer to specify the transaction configured in DataSourceConfig.

The second is to use jta-atomikos to implement distributed transaction management.

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

When creating a new Spring Boot project, there is a parent by default. This parent is spring-boot-starter-parent, and spring-boot-starter-parent mainly has the following functions:

  1. Defines the Java compilation version.
  2. Encoded using UTF-8 format.
  3. Configuration for performing packaging operations.
  4. Automated resource filtering.
  5. Automated plugin configuration.
  6. Resource filtering for application.properties and application.yml, including configuration files for different environments defined by profile, such as application-dev.properties and application-dev.yml.

What is the difference between the jar made by Spring Boot and the ordinary jar?

  • The final packaged jar of the Spring Boot project is an executable jar. This kind of jar can be run directly through java -jar xxx.jarcommands . This kind of jar cannot be relied on by other projects as a normal jar, and even if it is relied on, the classes in it cannot be used.
  • Spring Boot's jar cannot be relied upon by other projects, mainly because it has a different structure from ordinary jars. Ordinary jar package, after decompression, is the package name directly, and our code is in the package, while the executable jar packaged by Spring Boot is our code in \BOOT-INF\classesthe directory referenced. If you have to quote, you can add configuration to the pom.xml file and package the Spring Boot project into two jars, one executable and one referenceable.

The idea of ​​SpringBoot multi-data source splitting

First configure two data sources in the properties configuration file, create a subpackage mapper, use @ConfigurationProperties to read the configuration in properties, and use @MapperScan to register to the corresponding mapper package.

Guess you like

Origin blog.csdn.net/Tyson0314/article/details/130446485