SpringBoot custom starter and automatic configuration

The core SpringBoot is automatically configured, and is automatically configured to support one starter project. In addition to the existing official starter, users themselves can customize their starter project according to the rules.

Custom starter condition

Automated configuration must meet the following conditions:

  • The condition check classpath corresponding lower class, i.e. a corresponding need to provide a class can be checked;
  • It can be generated when the condition defined by Bean, and to register into the container;
  • You can automatically configure the required configuration items;

Custom spring boot starter

Here starter created by maven project management tool. First we need to create a simple maven project. Here we integrated a text message services, for example, to create a project.

Create a maven project

Maven project to create a simple, concrete steps are omitted. Can be created by intellj idea such as IDE, you can also be created using the maven command.

Directory structure is as follows:

.
├── pom.xml
├── spring-boot-starter-msg.iml
└── src
    ├── main
    └── test复制代码

Introduced in pom.xml SpringBoot automated configuration dependent spring-boot-autoconfigure:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-autoconfigure</artifactId>
    <version>2.1.5.RELEASE</version>
</dependency>复制代码

Services Service category definitions

Service defined service class, there are two effects, a project for the introduction of functional services province, a further determination based upon springboot configured to automatically.

MsgService a class defined herein.

package com.secbro2.msg;

import com.secbro2.utils.HttpClientUtils;

public class MsgService {

    /**
     * 访问发送短信的url地址
     */
    private String url;

    /**
     * 短信服务商提供的请求keyId
     */
    private String accessKeyId;

    /**
     * 短信服务商提供的KeySecret
     */
    private String accessKeySecret;

    public MsgService(String url, String accessKeyId, String accessKeySecret) {
        this.url = url;
        this.accessKeyId = accessKeyId;
        this.accessKeySecret = accessKeySecret;
    }

    public int sendMsg(String msg) {
        // 调用http服务并发送消息,返回结果
        return HttpClientUtils.sendMsg(url, accessKeyId, accessKeySecret, msg);
    }

    // 省略getter/setter方法
}
复制代码

MsgService which uses a utility class HttpClientUtils. In HttpClientUtils simply print the parameters of the requested information.

package com.secbro2.utils;

public class HttpClientUtils {

    public static int sendMsg(String url, String accessKeyId, String accessKeySecret, String msg) {
        //TODO 调用指定url进行请求的业务逻辑
        System.out.println("Http请求,url=" + url + ";accessKeyId=" + accessKeyId + ";accessKeySecret=" + accessKeySecret + ";msg=" + msg);
        return 0;
    }
}复制代码

Custom configuration class

MsgProperties configuration defined class, for the base configuration of the package application.properties or application.yml. Here on configuring a prefix of uniform application of SMS msg.

@ConfigurationProperties(prefix = "msg")
public class MsgProperties {

    /**
     * 访问发送短信的url地址
     */
    private String url;

    /**
     * 短信服务商提供的请求keyId
     */
    private String accessKeyId;

    /**
     * 短信服务商提供的KeySecret
     */
    private String accessKeySecret;
    
    // 其他参数定义
    // 省略getter/setter方法

}复制代码

It is assembled by @ConfigurationProperties corresponding attribute annotations.

Create automated configuration class

Automatic configuration class is a plain java class, given their different functions to different notes. One of the most core of the course is @Configuration comment.

@Configuration
@ConditionalOnClass(MsgService.class)
@EnableConfigurationProperties(MsgProperties.class)
public class MsgAutoConfiguration {

    /**
     * 注入属性配置类
     */
    @Resource
    private MsgProperties msgProperties;

    @Bean
    @ConditionalOnMissingBean(MsgService.class)
    @ConditionalOnProperty(prefix = "msg", value = "enabled", havingValue = "true")
    public MsgService msgService() {
        MsgService msgService = new MsgService(msgProperties.getUrl(), msgProperties.getAccessKeyId(),
                msgProperties.getAccessKeySecret());
        // 如果提供了其他set方法,在此也可以调用对应方法对其进行相应的设置或初始化。
        return msgService;
    }
}复制代码

MsgAutoConfiguration based on the annotation, @ Configuration class is used to declare a configuration class; @ConditionalOnClass explanatory notes only when MsgService class will be present in the classpath corresponding instantiated; @EnableConfigurationProperties the corresponding property configuration application.properties MsgProperties disposed in the subject;

Annotations on msgService method, @ Bean show that the method instantiates objects which will be loaded into the container; @ConditionalOnMissingBean further specified example of when an object is not present MsgService containers; @ConditionalOnProperty specified in the configuration file msg.enabled = true when the corresponding instantiated.

Add spring.factories

When all the underlying code and auto-configuration classes are ready, you need to be registered. That is, we are familiar with the META-INF / spring.factories configuration files. Of course, this needs to be created in your own projects.

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.secbro2.msg.MsgAutoConfiguration复制代码

Sign MsgAutoConfiguration class spring.factories profile. If there are multiple classes autoconfiguration, can be separated by commas newline.

At this point, based on the auto-configuration starter Spring Boot is complete. Use "maven: install" package it in a local maven repository or upload to PW. Other projects will be able to rely on the use by maven.

Use starter project

In other projects, the introduction of the dependency by dependency.

<dependency>
    <groupId>com.secbro2</groupId>
    <artifactId>spring-boot-starter-msg</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>复制代码

Application.properties then disposed in the current project the corresponding parameters:

msg.enabled=true
msg.url=127.0.0.1
msg.accessKeyId=10001
msg.accessKeySecret=afelwjfwfwef复制代码

Other projects such as Spring Boot is also a project, you can define a simple Controller for testing.

@RestController
public class HelloWorldController {

    @Resource
    private MsgService msgService;

    @RequestMapping("/sendMsg")
    public String sendMsg(){
        msgService.sendMsg("测试消息");
        return "";
    }
}复制代码

When accessed through a browser: http: // localhost: 8080 / sendMsg, the log will be printed out as follows:

Http请求,url=127.0.0.1;accessKeyId=10001;accessKeySecret=afelwjfwfwef;msg=测试消息复制代码

DESCRIPTION MsgService object is automatically configured, and test.

And send text messages for such a starter, can be further expanded, to implement various basic functions of text messages sent, and when only other items needed to introduce corresponding dependence, and configure specific parameters can be used immediately, is not very convenient?

Summing up the work flow in the Starter:

  • Spring Boot scanning project depends JAR package when you start looking package contains spring.factories JAR files;
  • The spring.factories AutoConfiguration class loading configuration;
  • The conditions @Conditional annotations, automatic configuration and injection Bean Spring container.


New Horizons program : exciting and growth are not to be missed

New Horizons program - micro-channel public number

Guess you like

Origin juejin.im/post/5dc375d75188255f9a287d34