SpringBoot自定义启动器

根据SpringBoot自动配置原理,我们自己也能写出自定义自动配置原理SpringBoot的starter启动器

最终目录

SpringBoot自定义启动器_第1张图片

接下来写一个HelloWorld的简单启动器

引入依赖


        
            org.springframework.boot
            spring-boot-autoconfigure
            2.1.4.RELEASE
        
        
            junit
            junit
            4.12
        
        
            org.springframework.boot
            spring-boot-configuration-processor
            2.1.4.RELEASE
        
    

自定义启动器名称与版本

pom.xml中可修改

com.tpa
spring-boot-starter-tpa
1.0-SNAPSHOT

属性配置类

@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;
    }
}

判断依据类

根据此类的存在与否来创建这个类的bean

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;
    }
}

自动配置类

根据HelloServiceProperties提供的参数,并通过@ConditionalOnClass判断HelloService这个类在类路径中是否存在,且当容器中没有这个Bean的情况下自动配置这个bean

@Configuration
@EnableConfigurationProperties(HelloServiceProperties.class)
@ConditionalOnClass(HelloService.class)
public class HelloServiceAutoConfiguration {

    @Autowired
    private HelloServiceProperties helloServiceProperties;

    @Bean
    @ConditionalOnMissingBean(HelloService.class)
    public HelloService helloService(){
        HelloService helloService = new HelloService();
        helloService.setMsg(helloServiceProperties.getMsg());
        return helloService;
    }
}

注册配置

src/main/resources下新建META-INF/spring.factories

如果有多个自动配置,则用“,”隔开

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.tpa.service.HelloServiceAutoConfiguration

最后用maven打成jar包即可,自动存入maven仓库中

测试

在其他项目中引入我们的启动器依赖


    com.tpa
    spring-boot-starter-tpa
    1.0-SNAPSHOT

在这个类中没有创建HelloService类,但却可以直接调用HelloService及其API,说明我们的自定义启动器创建成功了

测试代码

SpringBoot自定义启动器_第2张图片

测试结果

 

你可能感兴趣的:(java,spring,boot,java)