search
HomeJavajavaTutorialWhat is the principle of java SpringBoot automatic assembly?

summary

detail

Traditional Spring projects will have many configuration files. For example, if we want to use Redis, generally in addition to the corresponding dependent jar packages, we also need to add them to application.xml Configure JedisConnectionFactory, JedisPoolConfig, and RedisTemplate. But if you use SpringBoot, the system will automatically generate these classes based on the jar package in pom.xml and inject them into the IOC container.

Configuration is required in traditional Spring projects

<bean id="jedisConnectionFactory" class="...JedisConnectionFactory"></bean>
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"></bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"></bean>

When using SpringBoot, in addition to introducing the corresponding jar package in pom.xml, you only need to configure the corresponding property values ​​​​in application.properties

Take Redis as an example

  • Get more than 120 default function configuration classes from spring-boot-autoconfigure.jar/META-INF/spring.factories, including the functions of redis The fully qualified name of the configuration class RedisAutoConfiguration. Generally, a functional configuration class revolves around this function and is responsible for managing and creating multiple related functional classes. For example, RedisAutoConfiguration is responsible for:

JedisConnectionFactory, RedisTemplate, and StringRedisTemplate. Creation of a functional class

org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
  • One condition for the RedisAutoConfiguration configuration class to take effect is @ConditionalOnClass: JedisConnection.class, RedisOperations.class, Jedis.class, so it will go to the classpath to find the corresponding class File

@Configuration
@ConditionalOnClass({ JedisConnection.class, RedisOperations.class, Jedis.class })
@EnableConfigurationProperties(RedisProperties.class)
public class RedisAutoConfiguration {}
  • If pom.xml has a corresponding jar package, it can match the corresponding dependency class: JedisConnection.class, RedisOperations.class, Jedis.class

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
  • If the match is successful, this function configuration class will take effect, and the default property configuration class @EnableConfigurationProperties(RedisProperties.class)

  • will be injected.
@ConfigurationProperties(prefix = "spring.redis")
public class RedisProperties {
    private int database = 0;
    private String url;
    private String host = "localhost";
    private String password;
    private int port = 6379;
  • The Redis function configuration will generate the final JedisConnectionFactory and RedisTemplate according to the conditions. The condition is that there are no user-defined ones in the IOC environment.

@ConditionalOnMissingBean(RedisConnectionFactory.class), RedisTemplate

@Configuration
@ConditionalOnClass({ JedisConnection.class, RedisOperations.class, Jedis.class })
@EnableConfigurationProperties(RedisProperties.class)
public class RedisAutoConfiguration {
        @Bean
        @ConditionalOnMissingBean(RedisConnectionFactory.class)
        public JedisConnectionFactory redisConnectionFactory()
                throws UnknownHostException {
            return applyProperties(createJedisConnectionFactory());
        }

        @Bean
        @ConditionalOnMissingBean(name = "redisTemplate")
        public RedisTemplate<Object, Object> redisTemplate(
                RedisConnectionFactory redisConnectionFactory)
                        throws UnknownHostException {
            RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
            template.setConnectionFactory(redisConnectionFactory);
            return template;
        }
}
  • The finally created default assembly class will be injected into the IOC through the @Bean annotation in the functional configuration class

Principle and result analysis

Through various annotations, SpringApplication.run(Application.class, args) will read the spring in spring-boot-autoconfigure.jar when running. Factories configuration file, the configuration file contains the className of the configuration class of all automatic assembly classes, and then generates the Configuration class corresponding to the function. If these function configuration classes are to take effect, they will go to the classpath to find whether there are dependent classes of this class (that is, pom .xml must have a jar package with corresponding functions), and then the final functional class is generated through judgment in the configuration class, and the default attribute value class is injected into the configuration class, and the functional class can be referenced and assigned a default value. The principle of generating functional classes is to give priority to customization. Automatic assembly classes will be used only when there is no customization.

To sum up, in order to automatically assemble a class, two conditions need to be met:

  • spring.factories contains a configuration class for this class (a The configuration class can create multiple dependent classes surrounding this function)

  • pom.xml needs to have the corresponding jar package

The result of the whole process is two things:

  • Based on various judgments and dependencies, the classes required by the business are finally generated and injected into the IOC container

  • The class generated by automatic assembly is given some default attribute values

Dependent annotations

  • @ SpringBootApplication: The annotation of the sb project application startup class is actually a combination of three annotations: @SpringBootConfiguration, @EnableAutoConfiguration, @ComponentScan, of which the second one

  • ## plays a role in automatic assembly. #@EnableAutoConfiguration: Indicates the function of SB application to start automatic assembly (including loading the corresponding Bean into the IOC container and assigning values ​​to properties according to the default configuration)

  • @Import(EnableAutoConfigurationImportSelector.class) : This annotation is quite powerful. You can forcibly register beans that are not registered in the IOC to the IOC, indicating that to start the automatic configuration function, you need to introduce EnableAutoConfigurationImportSelector.class

  • @Configuration

  • @ConditionalOnClass({ JedisConnection.class, RedisOperations.class, Jedis.class }): Indicates that for the RedisAutoConfiguration configuration class to work, there must be a jar package containing these classes.

  • @EnableConfigurationProperties(RedisProperties.class): Indicates that the configuration in RedisProperties.class is referenced by default

  • ##@ConditionalOnMissingBean(RedisConnectionFactory.class): This is very powerful Note, customization takes precedence when implementing automatic assembly. Indicates that the default JedisConnectionFactory will be used only if the user does not inject a custom RedisConnectionFactory.class class.

The process of automatic assembly

  • The dependency between classes is realized through various annotations. When the container starts, Application.run will Call the selectImports method of EnableAutoConfigurationImportSelector.class (actually the method of its parent class)

  • The selectImports method will eventually call the SpringFactoriesLoader.loadFactoryNames method to obtain a comprehensive list of commonly used BeanConfigurations

  • The loadFactoryNames method will read FACTORIES_RESOURCE_LOCATION (that is, spring.factories under spring-boot-autoconfigure.jar) and obtain the fully qualified ClassName of all Spring-related beans, about 120+

  • The selectImports method continues to call filter(configurations, autoConfigurationMetadata); at this time, it will be filtered one by one according to the conditions in these BeanConfigurations. The most important thing is @ConditionalOnClass. This conditional annotation will go to the classpath. Find whether there is this conditional dependency class in the jar package, so you must have the corresponding jar package to have these dependency classes and generate some default configuration beans required by the IOC environment

  • Finally, inject the qualified BeanConfiguration into the attribute value in the default EnableConfigurationPropertie class and inject it into the IOC environment

The above is the detailed content of What is the principle of java SpringBoot automatic assembly?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.