第16篇:自定义starter
流程
- 新建module:hello-spring-boot-starter-autoconfigure
- 新建module:hello-spring-boot-starter
- 新建工程,测试
1. 新建autoconfigure module
- 属性配置bean
@ConfigurationProperties("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; } }
- 对外提供的service
public class HelloService { private HelloProperties helloProperties; public HelloProperties getHelloProperties() { return helloProperties; } public void setHelloProperties(HelloProperties helloProperties) { this.helloProperties = helloProperties; } public String hello(String name) { return helloProperties.getPrefix() + "-" + name + "-" + helloProperties.getSuffix(); } }
- 自动配置
@Configuration @EnableConfigurationProperties(HelloProperties.class) public class HelloAutoConfiguration { @Autowired private HelloProperties helloProperties; @Bean public HelloService helloService() { HelloService helloService = new HelloService(); helloService.setHelloProperties(helloProperties); return helloService; } }
- spring.factories
resources下,创建文件:META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.hzk.app.hello.HelloAutoConfiguration
2. 新建module hello-spring-boot-starter
引入上面的autoconfigure
3. test
引入starter,添加hello
相关配置,注入HelloService