08.Spring Boot 之自定义 starter

1. 自定义 starter

通常来说,启动器只用来做依赖导入,没有任何代码,所以需要专门来写一个自动配置模块

如果是 Spring Boot 内部提供的组件,一般叫 spring-boot-starter-xxx,如果是第三方组件集成 Spring Boot,一般是叫 xxx-spring-boot-starter,如 mybatis-spring-boot-starter

2. 环境搭建

代码已经上传至 https://github.com/masteryourself-tutorial/tutorial-spring ,详见 tutorial-spring-boot-core/tutorial-spring-boot-starter 工程

2.1 sample-spring-boot-starter-autoconfigure

自动配置模块

2.1.1 配置文件
1. META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  pers.masteryourself.tutorial.spring.boot.starter.sample.SampleAutoConfiguration
2.1.2 核心代码
1. SampleAutoConfiguration
@Configuration
@ConditionalOnClass(SampleService.class)
@EnableConfigurationProperties(SampleProperties.class)
public class SampleAutoConfiguration {

    private SampleProperties properties;

    public SampleAutoConfiguration(SampleProperties properties) {
        this.properties = properties;
    }

    @Bean
    public SampleService sampleService() {
        return new SampleService(properties);
    }

}
2. SampleService
public class SampleService {

    private SampleProperties properties;

    public SampleService(SampleProperties properties) {
        this.properties = properties;
    }

    public String say(String str) {
        return properties.getPrefix() + " [" + str + "] " + properties.getSuffix();
    }

}
3. SampleProperties
@Data
@ConfigurationProperties(prefix = "sample")
public class SampleProperties {

    private String prefix;

    private String suffix;

}
2.2 sample-spring-boot-starter

自定义启动器,无任何代码,只做依赖

2.2.1 配置文件
1. pom.xml
<dependencies>
    <dependency>
        <groupId>pers.masteryourself.tutorial.spring</groupId>
        <artifactId>sample-spring-boot-starter-autoconfigure</artifactId>
    </dependency>
</dependencies>
2.3 sample-spring-boot-starter-test

测试工程

2.3.1 配置文件
1. application.properties
sample.prefix=author:masteryourself
sample.suffix=created
2.3.2 核心代码
1. SampleServiceTestApplication
@SpringBootApplication
public class SampleServiceTestApplication implements CommandLineRunner {

    @Autowired
    private SampleService sampleService;

    public static void main(String[] args) {
        SpringApplication.run(SampleServiceTestApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println(sampleService.say("hello"));
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值