一、简介
Spring Boot中有很多的启动器(Starter),也是Spring Boot最强大的特点,就是把所有场景抽取成了一个个的启动器,我们只要依赖它的启动器,就可以使用它的功能,还提供相应的自动配置。
二、自定义starter
步骤:启动器只用来做依赖导入==>专门来写一个自动配置模块==>启动器依赖自动配置。
新建一个空工程>再建一个starter的模块>再建一个autoconfigurer的模块
starter模块只要依赖autoconfigurer模块
com.starter.demo
demo2-spring-boot-starter-autocofiguraer
0.0.1-SNAPSHOT
接下来我们在做一个autoconfigurer模块说hello的Demo
Step 1:所有starter必须引入的starter基本配置
org.springframework.boot
spring-boot-starter
Step 2:先编写一个properties的配置类
@ConfigurationProperties(prefix = "eh.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;
}
}
Step 3:编写说hello的服务类
public class HelloService {
private HelloProperties helloProperties;
public HelloProperties getHelloProperties() {
return helloProperties;
}
public void setHelloProperties(HelloProperties helloProperties) {
this.helloProperties = helloProperties;
}
public String sayHelloWorld(String name){
return helloProperties.getPrefix()+"-"+name+helloProperties.getSuffix();
}
}
Step 4:编写一个调用的自动配置类
// 加入容器
@Configuration
// @ConditionalOnxxx WebApplication :表示Web程序才生效
@ConditionalOnWebApplication
//启用配置属性类
@EnableConfigurationProperties(HelloProperties.class)
public class HelloServiceAutoConfiguration {
@Autowired
HelloProperties helloProperties;
@Bean
public HelloService helloService(){
HelloService helloService = new HelloService();
helloService.setHelloProperties(helloProperties);
return helloService;
}
}
Step 5:在spring.factories中启动
Strong Boot启动时会加载 spring.factories 中的配置,所以最终要在 spring.factories 中配置才会生效,在META-INF下新建 spring.factories 文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.eh.starter.HelloServiceAutoConfiguration
到此已经完成了,接下来只是测试了,新建一个工程>依赖启动器>配置 application.yml/properties >编写controller方法
pom.xml
org.springframework.boot
spring-boot-starter-web
com.demo.starter
demo2-spring-boot-starter
1.0-SNAPSHOT
application.properties
eh.hello.prefix="spring-boot"
eh.hello.suffix="Hello Word"
controller
@RestController
public class TestController {
@Autowired
HelloService helloService;
@GetMapping("test/{name}")
public String test(@PathVariable("name") String name){
return helloService.sayHelloWorld(name);
}
}