自动配置工程
-
绑定配置文件,上逼格的 start 都支持自定义配置,我们也装像点~~
@ConfigurationProperties("cyrus.hello") public class CyrusHelloProperties { // 绑定配置文件 cyrus.hello.username 属性 private String username; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
-
start 核心业务功能
// 这里没有 @Configuration,因为要自动配置 public class HelloService { @Autowired private CyrusHelloProperties cyrusHelloProperties; public String sayHello(String username){ return cyrusHelloProperties.getUsername() + "你好"; } }
-
start 自动配置
@Configuration @EnableConfigurationProperties(CyrusHelloProperties.class) public class CyrusHelloAutoConfiguration { @ConditionalOnMissingBean(HelloService.class) @Bean public HelloService helloService(){ return new HelloService(); } }
start 工程
-
resource/META-INF 下创建 spring.factories 文件,文件内容如下
# Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.cyrus.hello.autoconfigure.CyrusHelloAutoConfiguration
-
pom 引入自动配置工程,引入 start 自动引入其所需依赖
<dependencies> <dependency> <groupId>curus-hello</groupId> <artifactId>cyrus-hello-spring-boot-autoconfigure</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> </dependencies>