SpringBoot自定义启动器

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

最终目录

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

引入依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>2.1.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <version>2.1.4.RELEASE</version>
        </dependency>
    </dependencies>

自定义启动器名称与版本

pom.xml中可修改

<groupId>com.tpa</groupId>
<artifactId>spring-boot-starter-tpa</artifactId>
<version>1.0-SNAPSHOT</version>

属性配置类

@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仓库中

测试

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

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

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

测试代码

测试结果

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值