建立工程
我们首先建一个maven工程,可以按照SpringBoot的规范取名为spring-boot-starter-XX
- 依赖
//这个类是为了自动装配
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
//下面链接是官网对于这个以来的解释
//https://docs.spring.io/spring-boot/docs/2.1.0.RELEASE/reference/html/configuration-metadata.html#configuration-metadata-annotation-processor
//这个依赖是为了读取配置文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.1.0.RELEASE</version>
<optional>true</optional>
</dependency>
-
项目结果
项目结果.png - PhoneProperties(属性配置类)
使用@ConfigurationProperties读取配置文件中的参数,并且设置有默认值
@ConfigurationProperties(prefix = "spring.phone")
public class PhoneProperties {
private String name = "小米";
private Integer storage = 1024;
private String money = "1299rmb";
//get set 方法
}
-
PhoneAutoConfiguration(核心自动装配类)
@Configuration
@EnableConfigurationProperties 转载配置类
@ConditionalOnClass 如果此class不存在
@Conditional是什么
@Configuration
@EnableConfigurationProperties(PhoneProperties.class)
@ConditionalOnClass(PhoneService.class)
@ConditionalOnProperty(prefix = "spring.phone",value = "enable", matchIfMissing = true)
public class PhoneAutoConfiguration {
@Autowired
PhoneProperties phoneProperties;
@Bean
@ConditionalOnMissingBean(PhoneService.class)
public PhoneService getPhoneService(){
return new PhoneService(phoneProperties);
}
}
- PhoneService(具体服务类)
服务类为具体需要注入的服务。 - spring.factories
spring的一种扩展手段,通过加载的时候SpringFactoriesLoader读取spring.factories文件中的EnableAutoConfiguration数据对应的配置项通过反射(Java Refletion)实例化为对应的标注了@Configuration的JavaConfig形式的IoC容器配置类,然后汇总为一个bean加载到IoC容器。
org.springframework.boot.autoconfigure.EnableAutoConfiguration=
com.example.springbootstarterphone.config.PhoneAutoConfiguration