The starter background

One of the main reasons Spring Boot has become one of the must-have skills for back-end development is that there is a very important mechanism in Spring Boot (the starter mechanism).

The starter can discard complex configurations and integrate them into the starter. You only need to introduce the corresponding starter dependency in Maven, and Spring Boot can automatically scan the information to be loaded and start the corresponding default configuration.

Starter frees us from having to rely on libraries for processing and configuration information. SpringBoot automatically finds the beans it needs through classes in the classpath path and registers them with the IOC container. Spring Boot provides the spring-boot-starter dependency module for daily enterprise application development scenarios. All of these dependency modules follow the conventions of default configurations and allow us to tweak those configurations, following the “convention over configuration” philosophy.

[Jin SAN Yin Si, how to increase salary see here]

We often see and use a variety of XXX-starter. Such as the following:

Spring Boot Starter principle

In general, this is nothing more than importing Jar packages into the project as dependencies for the project. Now the difficulty is increased because we introduce Spring Boot Starter, so we need to understand how Spring Boot to Spring Boot Starter Jar package is loaded? So let me just say a few words.

SpringBoot looks for/meta-INF /spring.factories files in the starter package it depends on when starting up, and then scans the Jar packages that the project depends on according to the Jar packages configured in the file. This is similar to Java’s SPI mechanism.

In detail, the @Conditional series of annotations can be used to more precisely configure the conditions for loading beans.

JavaSPI is actually a dynamic loading mechanism implemented by a combination of interface-based programming + policy pattern + configuration files.

Conditions for customizing the starter

To customize the Starter, automatic configuration is preferred. The automatic configuration must meet the following requirements:

  1. Can automatically configure the configuration information required by the project, that is, automatically load dependent environment;

  2. The ability to automatically generate beans based on the information provided by the project and register them with the Bean management container;

Implement custom starter

Pom. XML dependency

<dependencies>
 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-autoconfigure</artifactId>
    <version>. 2.0.0 RELEASE</version>
 </dependency>
 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <version>. 2.0.0 RELEASE</version>
    <optional>true</optional>
  </dependency>
</dependencies>
Copy the code

The implementation process of a customized Starter is as follows (the Starter I defined is taken as an example) :

Define the XxxProperties class, the property configuration class, and perform property configuration related operations, such as setting property prefixes, to be configured in application.properties.

TianProperties code:

import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "spring.tian")
public class TianProperties {
    private String name;
    private int age;
    private String sex = "M";
    // omit the get set method
}
Copy the code

Create the XxxService class to complete the operation logic.

TianService code:

public class TianService {

    private TianProperties properties;

    public TianService(a) {}public TianService(TianProperties userProperties) {
        this.properties = userProperties;
    }
    public void sayHello(a){
        System.out.println("Hi, my name is:" + properties.getName() +
        This year, "," + properties.getAge() + "Age"
         + ", gender:+ properties.getSex()); }}Copy the code

Define XxxConfigurationProperties, automatic configuration, used to complete Bean creation, etc.

TianServiceAutoConfiguration code:

@Configuration
@EnableConfigurationProperties(TianProperties.class)
@ConditionalOnClass(TianService.class)
@ConditionalOnProperty(prefix = "spring.tian", value = "enabled", matchIfMissing = true)
public class TianServiceAutoConfiguration {

    @Autowired
    private TianProperties properties;

    @Bean
    @ConditionalOnMissingBean(TianService.class)
    public TianService tianService(a) {
        return newTianService(properties); }}Copy the code

Create a meta-INF directory under Resources and spring.factories under meta-INF to load the automatic configuration classes for your project when SpringBoot starts.

“Spring. Factories Configured”

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.tian.TianServiceAutoConfiguration
Copy the code

Jar the starter project as follows:

Use a custom starter

Create a Spring Boot project test, as shown below:

Add a custom starter to your project with poM dependencies

<dependency>
    <groupId>com.tian</groupId>
    <artifactId>spring-boot-tian-starter</artifactId>
    <version>1.0 the SNAPSHOT</version>
</dependency>

Copy the code

TestApplication start class

@SpringBootApplication
@EnableEurekaServer
public class TestApplication {
    public static void main(String[] args) { SpringApplication.run(TestApplication.class, args); }}Copy the code

Application. The properties in the configuration

spring.tian.name=tian
spring.tian.age=22
spring.tian.sex=M
Copy the code

Write a testController.java class

RestController
@RequestMapping("/my")
public class TestController {

    @Resource
    private TianService tianService;

    @PostMapping("/starter")
    public Object starter(a) {
        tianService.sayHello();
        return "ok"; }}Copy the code

After adding our custom starter jar dependency,

You can see that there is an extra JSON file.

Finally launch the project, enter

http://localhost:9091/my/starter

Controller returns OK successfully, and then look at background printing

Hi, MY name is Tian. I am 22 years old and my gender is MCopy the code

This is the success of a custom starter.

Key words: out of the box, reduce a large number of configuration items, convention than configuration.

conclusion

  1. Spring Boot scans the JAR packages that the project depends on at startup, looking for the JAR packages that contain the Spring.factories files,

  2. Then read the Spring. factories file to get the AutoConfiguration class for the configuration,

  3. Then place the @bean that meets the condition (@conditionalonxxx) in the auto-configuration class into the Spring Context.

  4. This allows the user to inject directly because the class is already in the container.

“As long as we are in the right direction, we are not afraid of a long road!”