本文章记录了SpringBoot如何自定义starter
一、首先创建启动器
1、创建一个空的工程
2、建议对应的module,选择maven来进行创建
定义对应的GroupId 和ArtifactId
定义对应的Module名称
二、接下来创建springboot的初始化器,创建自动配置的相关的东西
1、新建module,选择spring initializr来进行创建
创建后不引入任何模块点击next,创建生成
三、启动器中引入自动配置模块
删除自动配置文件
删除配置器多余的依赖,只留下starter
四、创建自动配置类对应的Properties类
@ConfigurationProperties(prefix = "training.hello")
public class HelloProperties {
private String prefix;
private String suffix;
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
}
五、自定义测试的服务类
public class HelloService {
HelloProperties helloProperties;
public HelloProperties getHelloProperties() {
return helloProperties;
}
public void setHelloProperties(HelloProperties helloProperties) {
this.helloProperties = helloProperties;
}
public String sayHello(String name){
return helloProperties.getPrefix()+"-"+name+"-"+helloProperties.getSuffix();
}
}
六、定义自动配置类
@Configuration
@ConditionalOnWebApplication
@EnableConfigurationProperties(HelloProperties.class)
public class HelloAutoConfiguration {
@Autowired
HelloProperties helloProperties;
@Bean
public HelloService helloService(){
HelloService helloService = new HelloService();
helloService.setHelloProperties(helloProperties);
return helloService;
}
}
编写完后需要在配置模块中创建spring.factories并把自动配置类配置到配置文件中
META-INF/spring.factories
七、打包
分别将配置类和启动类install,先执行配置类的install,然后执行启动类的install,打包到本地
八、编写测试工程,在工程中引入依赖
<dependency>
<groupId>com.training.starter</groupId>
<artifactId>training-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
编写controller进行测试
@RestController
public class HelloController {
@Autowired
HelloService helloService;
@GetMapping("/hello")
public String Hello(){
return helloService.sayHello("AA");
}
}
在配置文件中添加外置属性
training.hello.prefix="BB1"
training.hello.suffix="Hello Word"