1. spring 框架中的 starter
spring 自动配置的依赖,:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
springboot 框架本身大量组件的自动配置就是通过spring-boot-autoconfigure 实现的:
spring.factories 文件 EnableAutoConfiguration 后面配置了大量的自动配置类:
拿 jpa 的starter 举个例子:
@Configuration
@ConditionalOnBean(DataSource.class)
@ConditionalOnClass(JpaRepository.class)
@ConditionalOnMissingBean({ JpaRepositoryFactoryBean.class,
JpaRepositoryConfigExtension.class })
@ConditionalOnProperty(prefix = "spring.data.jpa.repositories", name = "enabled", havingValue = "true", matchIfMissing = true)
@Import(JpaRepositoriesAutoConfigureRegistrar.class)
@AutoConfigureAfter(HibernateJpaAutoConfiguration.class)
public class JpaRepositoriesAutoConfiguration {
}
spring.factories 配置了上述配置类,JpaRepositoriesAutoConfiguration 会根据各类条件选择性加载。
org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration
通过 conditionOnXXx 注解,先判断spring容器是否已经加载相应的资源,且配置开关是开启的,spring 容器 jpa相关 bean 还没初始化,才会就行jpa配置的初始化;AutoConfigureAfter 注解配置了这个类的初始化顺序
jpa 配置是在HibernateJpaAutoConfiguration初始化之后再执行的:
@Configuration
@ConditionalOnClass({ LocalContainerEntityManagerFactoryBean.class, EntityManager.class })
@Conditional(HibernateEntityManagerCondition.class)
@EnableConfigurationProperties(JpaProperties.class)
@AutoConfigureAfter({ DataSourceAutoConfiguration.class })
@Import(HibernateJpaConfiguration.class)
public class HibernateJpaAutoConfiguration {
@Order(Ordered.HIGHEST_PRECEDENCE + 20)
static class HibernateEntityManagerCondition extends SpringBootCondition {
private static final String[] CLASS_NAMES = {
"org.hibernate.ejb.HibernateEntityManager",
"org.hibernate.jpa.HibernateEntityManager" };
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
ConditionMessage.Builder message = ConditionMessage
.forCondition("HibernateEntityManager");
for (String className : CLASS_NAMES) {
if (ClassUtils.isPresent(className, context.getClassLoader())) {
return ConditionOutcome
.match(message.found("class").items(Style.QUOTE, className));
}
}
return ConditionOutcome.noMatch(message.didNotFind("class", "classes")
.items(Style.QUOTE, Arrays.asList(CLASS_NAMES)));
}
}
2. 自定义 starter
pom 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
在 META-INF/spring.factories 中配 org.springframework.boot.autoconfigure.EnableAutoConfiguration =自己的配置类
配置类使用的注解有:
Configuration 注解
EnableConfigurationProperties 注解
NestedConfigurationProperty 注解
import 注解
ConditionalOnProperty注解
ConditionalOnClass注解
ConditionalOnMissingBean 注解
AutoConfigureAfter 注解