1、自动配置原理
注解依赖:
- @SpringBootApplication
- @EnableAutoConfiguration:启用 SpringBoot 的自动配置机制,通过Spring 提供的 @Import 注解导入了AutoConfigurationImportSelector类
@AutoConfigurationPackage
@Import({org.springframework.boot.autoconfigure.AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
java.lang.String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
java.lang.Class<?>[] exclude() default {};
java.lang.String[] excludeName() default {};
}
AutoConfigurationImportSelector类中getCandidateConfigurations方法会将所有自动配置类的信息
以List 的形式返回。这些配置信息会被 Spring 容器作bean来管理。
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
return configurations;
}
public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
String factoryClassName = factoryClass.getName();
return loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
}
@EnableAutoConfiguration找到META-INF/spring.factories,读取每个starter中的spring.factories文件
private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
MultiValueMap<String, String> result = cache.get(classLoader);
if (result != null) {
return result;
}
try {
// FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories"
Enumeration<URL> urls = (classLoader != null ?
classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
result = new LinkedMultiValueMap<>();
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
UrlResource resource = new UrlResource(url);
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
for (Map.Entry<?, ?> entry : properties.entrySet()) {
List<String> factoryClassNames = Arrays.asList(
StringUtils.commaDelimitedListToStringArray((String) entry.getValue()));
result.addAll((String) entry.getKey(), factoryClassNames);
}
}
cache.put(classLoader, result);
return result;
}
}
Spring Boot启动的时候会通过@EnableAutoConfiguration注解找到META-INF/spring.factories配置文件中的所有自动配置类,并对其进行加载,而这些自动配置类都是以AutoConfiguration结尾来命名的,它实际上就是一个JavaConfig形式的Spring容器配置类,它能通过以Properties结尾命名的类中取得在全局配置文件中配置的属性如:server.port,而XxxxProperties类是通过@ConfigurationProperties注解与全局配置文件中对应的属性进行绑定的。
2、默认配置信息设置
每一个XxxxAutoConfiguration自动配置类都是在某些条件之下才会生效的,这些条件的限制在Spring Boot中以注解的形式体现,常见的条件注解有如下几项:
注解 | 说明 |
---|---|
@ConditionalOnClass | 指定的类必须存在于类路径下 |
@ConditionalOnMissingClass | 当类路径下不存在指定类的条件下 |
@ConditionalOnBean | 容器中是否有指定的Bean |
@ConditionalOnMissingBean | 当容器里不存在指定bean的条件下 |
@ConditionalOnProperty | 指定的属性是否有指定的值 |
这些注解都组合了@Conditional注解,只是使用了不同的条件组合最后为true时才会去实例化需要实例化的类,否则忽略
外部类的自动条件配置:
以ServletWebServerFactory配置类为例:
ServletWebServerFactoryAutoConfiguration 类中使用@ConditionalOnClass指定了容器中必须有ServletRequest类或其实现类。所以,一般情况下ServletWebServerFactory配置类都会去实现 ServletRequest,这样自动将配置就完成了。
案例: Servlet自动配置属性
@Configuration
@ConditionalOnClass(ServletRequest.class)
@EnableConfigurationProperties(ServerProperties.class)
@Import({ ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class,
ServletWebServerFactoryConfiguration.EmbeddedTomcat.class,
ServletWebServerFactoryConfiguration.EmbeddedJetty.class,
ServletWebServerFactoryConfiguration.EmbeddedUndertow.class })
public class ServletWebServerFactoryAutoConfiguration{}
@org.springframework.context.annotation.Import({org.springframework.boot.context.properties.EnableConfigurationPropertiesImportSelector.class})
public @interface EnableConfigurationProperties {
java.lang.Class<?>[] value() default {};
}
@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true)
public class ServerProperties {
private Integer port;
private InetAddress address;
...
}
关于自定义自动配置可参考:springboot项目自定义starter
Spring4 中提供了更加通用的条件注解,让我们可以在满足不同条件时创建不同的 Bean,这种配置方式在Spring Boot 中得到了广泛的使用,大量的自动化配置都是通过条件注解来实现的.
3、自动配置注解
两个重要注解:@Conditional、@Profile
- 基本类
public interface Product {
String showName();
}
public class Huawei implements Product {
@Override
public String showName() {
return "华为";
}
}
public class Apple implements Product {
@Override
public String showName() {
return "苹果";
}
}
- 配置类
public class AppleCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata annotatedTypeMetadata) {
return COUNTRY_US.equals(context.getEnvironment().getProperty(COUNTRY));
}
}
public class HuaweiCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata annotatedTypeMetadata) {
return COUNTRY_CN.equals(context.getEnvironment().getProperty(COUNTRY));
}
}
@Configuration
public class JavaConfig {
public static final String COUNTRY = "country";
public static final String COUNTRY_CN = "cn";
public static final String COUNTRY_US = "us";
// 匹配规则
@Bean(COUNTRY)
@Conditional(HuaweiCondition.class)
Product huawei() {
return new Huawei();
}
@Bean(COUNTRY)
@Conditional(AppleCondition.class)
Product apple() {
return new Apple();
}
}
- 测试
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
// cn: 华为
ctx.getEnvironment().getSystemProperties().put(COUNTRY, COUNTRY_CN);
ctx.register(JavaConfig.class);
ctx.refresh();
Product book = (Product) ctx.getBean(COUNTRY);
System.out.println(book.showName());
}
使用@Profile配置
@Configuration
public class JavaConfig {
@Bean(COUNTRY)
@Profile(COUNTRY_CN)
Product huawei() {
return new Huawei();
}
@Bean(COUNTRY)
@Profile(COUNTRY_US)
Product apple() {
return new Apple();
}
}
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setActiveProfiles(COUNTRY_CN);
ctx.register(JavaConfig.class);
ctx.refresh();
Product product= (Product) ctx.getBean(COUNTRY);
// 华为
System.out.println(product.showName());
}