Hand tear SpringBoot's custom starter

I. Introduction

Hello, everyone. Recently, during the Golden Nine and Silver Ten days, many friends privately messaged Brother Hui, saying that they were asked how SpringBoot can customize the starter during the interview, but they didn’t know how to answer. So today, I will take everyone hand in hand to see how to implement a custom starter in SpringBoot.

2. What is SpringBoot automatic assembly?

Before implementing the code, let's take a look at what SpringBoot's automatic assembly is. Corresponding to automatic assembly is manual assembly. For example, when we used xml configuration files before, we needed to configure data sources, configure mybatis scans, configure database connection pools, etc. when introducing spring or importing mybatis.

In SpringBoot, we only need to introduce the corresponding mybatis starter, druid starter and database driver, and the configuration file can automatically and quickly complete the framework construction based on the configuration database address, user and password information. That is to say, as long as we introduce the starter and configure some necessary initialization connection parameters, we can use it directly without creating a lot of complicated configurations by ourselves to complete the dependencies between bean classes.

It all depends on SpringBoot's autowiring! And automatic assembly is inseparable from the core of the starter starter! So how is the starter starter implemented? In order to let everyone understand this problem, I will write a custom launcher for everyone.

3. Custom Launcher

1. The first step: first create a java-maven parent project

<?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.qfedu</groupId>
    <artifactId>springboot-auto</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/>
    </parent>
</project>

image.png

2. The second step: create a subproject

image.png

3. Introduce dependencies

<?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">
    <parent>
        <artifactId>springboot-auto</artifactId>
        <groupId>com.qfedu</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>demo</artifactId>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

4. Step 3: Create another submodule java2113-starter as the starter

image.png

5. Introduce dependencies

<dependencies>
    <!-- 引入springboot  自动装配核心注解  -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-autoconfigure</artifactId>
    </dependency>
</dependencies>

6. Step 4: Write the code

package com.qfedu.java2113;

public class HelloService {
    private String msg;
    public String sayHello(){
        return "hello" + msg;
    }
    
    public String getMsg() {
        return msg;
    }
    
    
    public void setMsg(String msg) {
        this.msg = msg;
    }
}

7. Write the configuration file: application.properties

hello.msg=byebye

8. Read the configuration data hello.msg of the configuration file in the HelloServiceProperties class

package com.qfedu.java2113;

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

// 读取配置文件中 以 hello为前缀的值 设置到  msg
@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;
    }
}

9. Complete the automatic configuration class HelloServiceAutoConfiguration.java

package com.qfedu.java2113;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/***
 * hello-2009-starter 启动器 对应的配置 类 HelloServiceAutoConfiguration
 * 每一个启动器都有一个 这样的配置类
 * HelloServiceAutoConfiguration 的 作用是
 * 将HelloServiceProperties 加入到容器
 * 将 HelloService 加入到容器 并且和  HelloServiceProperties 进行装配
 * HelloServiceAutoConfiguration 就是自动装配的配置类
 * 完成了 HelloServiceProperties  和 HelloService 之间的装配
 */
@Configuration //标记当前类是配置类,加载 HelloServiceProperties.class配置到容器中
@EnableConfigurationProperties(HelloServiceProperties.class)  // 让配置类HelloServiceProperties bean加入到容器中
public class HelloServiceAutoConfiguration {
    @Autowired
    private HelloServiceProperties helloServiceProperties;
    @Bean// 将HelloService 加入到容器
//    @ConditionalOnMissingBean(HelloService.class) // 只有当容器中没有 bean HelloService ,加入到容器,如果有就不需要加入到容器了
    public HelloService helloService(){
        HelloService helloService = new HelloService();
        helloService.setMsg(helloServiceProperties.getMsg());
        return helloService;
    }
}

image.png

10. Step 5: Let the automatic assembly class take effect

Create resources\META-INF\spring.factories in resources

# Auto Configure  让自定义的 自动配置类生效
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.qfedu.java2113.HelloServiceAutoConfiguration

11. Install to the local maven warehouse

Execute the mvn install command.

12. Step 6: Introduce the java2113-starter starter in the demo

image.png

13. Step 7: Write code and use a custom launcher

13.1 Configuration file initialization

image.png

13.2 Use

    @Autowired
    private HelloService helloService;
    
    @RequestMapping("/getHellMsg")
    public String getHellMsg(){
        return  "获取msg:"+ helloService.getMsg();
    }

14. Step 8: Test to see the effect

image.png

4. Summary

Ha, are you following along now? In this way, we have a good understanding of the operating principle of SpringBoot, especially the automatic assembly principle of SpringBoot, by customizing the starter. You can follow the implementation steps of Brother Hui above, step by step, as long as the effect comes out, and then reverse the implementation process. You will find that many so-called realization principles are not difficult.

Qianfeng Education Java Introduction Full Set of Video Tutorials (java core technology, suitable for java zero foundation, necessary for self-study of Java)

 

Guess you like

Origin blog.csdn.net/longz_org_cn/article/details/132034628