The principle of Spring Boot spring.factories

Article directory
        • 1. spring.factories usage
        • 2. spring.factories implementation principle
        • 3. What problems is spring.factories used to solve?
          • 3.1 Business scenario thinking and introduction of starter mechanism
          • 3.2 Spring Boot starter mechanism
        • 4. Summary

Recently, I saw the configuration of spring.factories being used in business code, and felt that the scenario was inappropriate. Moreover, there are few articles on the Internet that mention the causes and consequences of spring.factories and the starter mechanism. This article takes this opportunity to understand the usage and principles of spring.factories. general speaking,
Spring Boot’s spring.factories configuration mechanism is similar to Java SPI. The implementation class name of the interface is configured in the META-INF/spring.factories file in the engineering code, and then Spring Boot scans the configuration file at startup and instantiates the configuration. Bean in file. See the usage below in detail:

1. spring.factories usage
  • Spring Boot startup class MainApplication
package com.zqh.test.springfactories;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author fangchen
 * @date 2022-02-19 14:18
 */
@SpringBootApplication
public class MainApplication {<!-- -->

    public static void main(String[] args) {<!-- -->
        SpringApplication.run(MainApplication.class, args);
    }
}

  • META-INF/ spring.factories configuration class
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.zqh.test.springfactories.TestBean

  • TestBean.class Test Bean
package com.zqh.test.springfactories;

/**
 * @author fangchen
 * @date 2022-02-19 14:16
 */
public class TestBean {<!-- -->

    private Long id;

    public TestBean() {<!-- -->
        System.out.println("test bean init....");
    }

    public Long getId() {<!-- -->
        return id;
    }

    public void setId(Long id) {<!-- -->
        this.id = id;
    }
}

  • pom.xm maven dependency
<?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.zqh.test</groupId>
    <artifactId>springBootDemo</artifactId>
    <version>1.0-SNAPSHOT</version>


    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>2.6.3</version>
        </dependency>

    </dependencies>

</project>

Run the MainApplication class and the results are as follows. It can be seen that the TestBean class has been instantiated when Spring Boot starts.

2022-02-19 19:49:30.274 INFO 20112 --- [main] c.z.t.springfactories.MainApplication : Starting MainApplication using Java 1.8.0_221 on DESKTOP-ITB0Q9I with PID 20112 (D:\code\springBootDemo\target\ classes started by NINGMEI in D:\code\springBootDemo)
2022-02-19 19:49:30.276 INFO 20112 --- [main] c.z.t.springfactories.MainApplication: No active profile set, falling back to default profiles: default
test bean init.....
2022-02-19 19:49:30.614 INFO 20112 --- [main] c.z.t.springfactories.MainApplication : Started MainApplication in 0.595 seconds (JVM running for 0.864)

2. Spring.factories implementation principle

When Spring Boot starts, it first reads the class list of spring.factories, and then instantiates them one by one and puts them in the Spring context. The code is relatively simple, so I won’t go into details and just look at the picture.

  • Source code class: org.springframework.core.io.support.SpringFactoriesLoader (spring-core package)
3. What problems is spring.factories used to solve?

In daily development, there are usually many ways to inject beans into the Spring container, such as @Autowire, @Import annotations, etc. Why use the spring.factories configuration mechanism?

Personal understanding: When an application relies on a third-party jar package, the spring.factories configuration method allows beans in the third-party jar package to be selectively injected into the Spring container. The following uses the starter mechanism of Spring Boot to explain how to use the spring.factories configuration file.

3.1 Business scenario thinking and introduction of starter mechanism

First think about a scenario:The application needs to rely on RedisTemplate for caching operations. How to introduce configuration? Generally there are two ways:

  • Method 1: Manually inject the dependent RedisTemplate and other related beans into the business application one by one (such as @Autowire, @Configuration, etc.)
  • Method 2: Introduce the dependent RedisTemplate and other related beans into a configuration class and mark it as @Configuration

The first method is obviously not advisable, that is, it couples the business, and subsequent package upgrades are more troublesome. The second unified approach is more recommended and is very easy to manage. If you use method two to name the class marked @Configuration as RedisAutoConfiguration, then this class encapsulates the Bean that must be injected into Spring when introducing redis, and so on. When mysql is introduced later, the classes that mysql must depend on are encapsulated as DataSourceAutoConfiguration. That’s it. This happens to be exactly the internal principle of the Spring Boot starter mechanism, that is, the Spring Boot starter uniformly encapsulates each component into a fixed configuration class. For example, redis-related dependency classes are uniformly packaged into the RedisAutoConfiguration class, and the database dependency class is Unifiedly encapsulate it into the DataSourceAutoConfiguration class, etc., and then configure these unified configuration classes into the spring.factories file. When Spring Boot is started (the prerequisite is to configure the EnableAutoConfiguration annotation, which is also the origin of the EnableAutoConfiguration annotation), it will scan spring in the dependent jar package one by one. factories file, and finally inject these classes into the spring container, and the business can directly reference them.

3.2 Spring Boot starter mechanism

After understanding the above, the principles and definitions of the Spring Boot starter mechanism will be clearer. Let’s understand the following passage again: springboot starter is a plug-in mechanism that abandons the previous cumbersome configuration and integrates complex dependencies into the starter. The emergence of starter has greatly helped developers liberate themselves from tedious framework configuration, so as to focus more on business code. In addition, springboot officially provides starter dependency modules for different scenarios in addition to enterprise-level projects, which can be easily integrated into projects, such as The springboot project needs to rely on redis. We only need to add the spring-boot-starter-data-redis dependency and configure some necessary connection information to use it.

4. Summary

It seems better to understand spring.factories configuration from the principle of Spring Boot starter mechanism. As for the trick of introducing spring.factories configuration in order to implement Spring Boot starter mechanism, or spring.factories configuration first before having Spring Boot starter mechanism, then It’s unknown. In short, the spring.factories configuration provides convenience for Spring Boot’s automatic assembly, and the Spring Boot starter mechanism generated on this basis brings convenience to the development of many middleware.

If you reprint, please indicate the source! Welcome to follow the WeChat public account: Fang Chen’s blog

The knowledge points of the article match the official knowledge archives, allowing you to further learn related knowledge.

Java Skill TreeHomepageOverview
133624 people are studying the system

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 138933 people are learning the system