“约定优于配置”是Spring Boot倡导的一个思想,而其自动配置的特性则恰好体现了这一思想。有了自动配置,不仅简化了Maven的依赖配置,更重要的是摆脱了以往使用Spring框架开发时,所必须编写的一堆繁琐的xml配置文件。而要使用自动配置,我们也只需要简单的在依赖中引入Starter依赖即可,例如,要在Spring Boot中启用Spring MVC,我们只需要在pom文件中引入spring-boot-starter-web
依赖即可,其他配置将Spring Boot自动完成。
下面,我们试着简单封装自己的一个Starter实现。
在Starter命名规则上面,spring-boot-starter-xxx是官方提供的命名规则,非官方Starter的命名规则则建议为** xxx-spring-boot-starter**。
1 新建Spring Boot项目,添加Maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional><!--true表明该依赖不会间接传递->
</dependency>
2 定义服务类及属性配置类
@ConfigurationProperties(prefix = "test.service")
public class TestServiceProperties {
private String prop1;
private String prop2;
//getter,setter方法
}
public class TestService {
private String prop1;
private String prop2;
public TestService(TestServiceProperties testServiceProperties) {
this.prop1 = testServiceProperties.getProp1();
this.prop2 = testServiceProperties.getProp2();
}
//getter,setter方法
}
3 定义自动配置类
@Configuration
@ConditionalOnClass(TestService.class)
@EnableConfigurationProperties(TestServiceProperties.class)
public class TestServiceConfiguration {
@Autowired
private TestServiceProperties testServiceProperties;
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "test.service", value = "enabled", havingValue = "true")
public TestService testService(){
return new TestService(testServiceProperties);
}
}
@ConditionalOnClass用于指定classpath下存在某些类才生效,@ConditionalOnMissingBean表示IOC容器中缺失某些bean时生效,@ConditionalOnProperty则表示参数配置满足特定的值才生效,这些注解被称作条件化注解,常结合@Configuration注解使用。其他类似注解还有@ConditionalOnWebApplication,@ConditionalOnNotWebApplication,@ConditionalOnMissingClass,@ConditionalOnBean等。
4 创建spring.factories文件
在/resources文件夹下,新建META-INF文件夹,并在该文件夹下新建spring.factories文件:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
gdou.laixiaoming.springbootautoconfig.config.TestServiceConfiguration
以org.springframework.boot.autoconfigure.EnableAutoConfiguration为Key,以对应的自动配置类为Value进行配置。添加spring.factories配置后,在其他Spring Boot项目引入该starter依赖后,Spring Boot启动时会检查jar中是否存在/META-INF/spring.factories文件,并将自动将文件中指定的配置类加载到IOC容器中,以此完成自动配置。
最后,使用 mvn clean install命令将项目安装到本地仓库,这样一个Starter就完成了。
5 测试
新建Spring Boot项目,引入上面的Starter依赖,application.properties添加相应配置:
#指定该属性为true,配置类才会生效
test.service.enabled=true
test.service.prop1=val1
test.service.prop2=val2
这样TestService的配置就会在Spring Boot启动时自动完成了,而在使用的时候则可以简单通过@Autowire注入使用了:
@Autowired
TestService testService;