SpringBoot之自动装配原理
Springboot自动装配原理
springboot自动装配
springboo最核心的东西就是自动装配原理,那么自动装装配原理是什么呢?自动装配原理其实就是对strat提供好的xxxAutoConfiguration、配置文件进行读取,当读取完后就配置好这些类。
详说springboot自动装配
进入项目后,我们发现springboot为开发者提供了一个类,类里有个run方法,看上去很简单没什么东西需要了解,但是细心的你会发现这个类上有个注解@SpringBootApplication,这个注解表示的就是这个类是springboot的启动类也就是入口。
@SpringBootApplication
public class Demo2Application {
public static void main(String[] args) {
SpringApplication.run(Demo2Application.class, args);
}
}
点击这个注解后我们可以看到这个注解上面除了四个元注解还有三个注解,@ComponentScan表示扫描注解,那么@SpringBootConfiguration、@EnableAutoConfiguration又代表什么呢?我们点击进入@SpringBootConfiguration注解里面。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
....
}
@SpringBootConfiguration
进入注解后我们看到这个注解里面出现了@Configuration注解,@configuration注解代表这个类就是一个配置文件,功能等同于在spring中的Application.xml文件。那么就是说@SpringBootConfiguration注解想表达的意思就是在类上面添加了他,他就把这个类变成一个配置类。
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
@AliasFor(
annotation = Configuration.class
)
boolean proxyBeanMethods() default true;
}
我还是不放心,害怕springboot欺骗我,我继续点击@Configuration注解进入后发现他确实是个配置注解,这个注解里出了通用注解,剩下的也就是元注解。
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
@AliasFor(
annotation = Component.class
)
String value() default "";
boolean proxyBeanMethods() default true;
}
经过对源码的分析得到了明白了在类上标注@SpringBootConfiguration是把这个类声明为一个配置类。
流程图:
@EnableAutoConfiguration
我们回到@SpringBootApplication注解下,这里我们就要进入springboot自动装配的主题了。我们进入@EnableAutoConfiguration注解。这里面出现了两个注解,我们先去了解@AutoConfigurationPackage注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
.....
}
@AutoConfigurationPackage
进入AutoConfigurationPackage是发现这里导入了一个注册类,那么我们得求看看这个配置类里面都干了什么。
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {
....
}
Registrar.class 将主配置类 【即@SpringBootApplication标注的类】的所在包及包下面所有子包里面的所有组件扫描到Spring容器 ;
static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
register(registry, new PackageImports(metadata).getPackageNames().toArray(new String[0]));
}
@Override
public Set<Object> determineImports(AnnotationMetadata metadata) {
return Collections.singleton(new PackageImports(metadata));
}
}
流程图:
@Import(AutoConfigurationImportSelector.class)
我们回到@EnableAutoConfiguration注解下并进入@Import(AutoConfigurationImportSelector.class)注解导入的AutoConfigurationImportSelector类下。并这个getcandidataconfigurations()方法。
这个方法的意思是获得候选的配置,这里的getSpringFactoriesLoaderFactoryClass()方法,返回的就是我们最开始看的启动自动导入配置文件的注解类EnableAutoConfiguration
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
getBeanClassLoader());
Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
+ "are using a custom packaging, make sure that file is correct.");
return configurations;
}
这个方法又调用了 SpringFactoriesLoader 类的静态方法!我们进入SpringFactoriesLoader类loadFactoryNames() 方法
/**
* Load the fully qualified class names of factory implementations of the
* given type from {@value #FACTORIES_RESOURCE_LOCATION}, using the given
* class loader.
* <p>As of Spring Framework 5.3, if a particular implementation class name
* is discovered more than once for the given factory type, duplicates will
* be ignored.
* @param factoryType the interface or abstract class representing the factory
* @param classLoader the ClassLoader to use for loading resources; can be
* {@code null} to use the default
* @throws IllegalArgumentException if an error occurs while loading factory names
* @see #loadFactories
*/
public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
ClassLoader classLoaderToUse = classLoader;
if (classLoaderToUse == null) {
classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
}
String factoryTypeName = factoryType.getName();
return loadSpringFactories(classLoaderToUse).getOrDefault(factoryTypeName, Collections.emptyList());
}
我们继续点击查看 loadSpringFactories 方法,这个方法的大概意思就是先看缓存中是否有这个类的类加载器(这个类指的是需要自动装配的类),如果有就结束方法,没有就去找这个类的META-INF/spring.factorie文件。我们这个里是springboot的自动装配类,所以我们应该找到的是spring-boot-autoconfigure包下的META-INF下的spring.factories文件。
private static Map<String, List<String>> loadSpringFactories(ClassLoader classLoader) {
Map<String, List<String>> result = cache.get(classLoader);
if (result != null) {
return result;
}
result = new HashMap<>();
try {
Enumeration<URL> urls = classLoader.getResources(FACTORIES_RESOURCE_LOCATION);
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
UrlResource resource = new UrlResource(url);
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
for (Map.Entry<?, ?> entry : properties.entrySet()) {
String factoryTypeName = ((String) entry.getKey()).trim();
String[] factoryImplementationNames =
StringUtils.commaDelimitedListToStringArray((String) entry.getValue());
for (String factoryImplementationName : factoryImplementationNames) {
result.computeIfAbsent(factoryTypeName, key -> new ArrayList<>())
.add(factoryImplementationName.trim());
}
}
}
// Replace all lists with unmodifiable lists containing unique elements
result.replaceAll((factoryType, implementations) -> implementations.stream().distinct()
.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)));
cache.put(classLoader, result);
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load factories from location [" +
FACTORIES_RESOURCE_LOCATION + "]", ex);
}
return result;
}
这个文件中全是xxxAutoConfigruation的路径,那么springboot通过反射这个这些类。
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration
# AutoConfigureDataCassandra auto-configuration imports
org.springframework.boot.test.autoconfigure.data.cassandra.AutoConfigureDataCassandra=\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
......
我们在这些类路劲中随便找一个类来看看。
我们以HttpEncodingAutoConfiguration(Http编码自动配置)为例解释自动配置原理;发现这个类下面又有几个注解,那么我先对注解一一解释。
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(ServerProperties.class)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnClass(CharacterEncodingFilter.class)
@ConditionalOnProperty(prefix = "server.servlet.encoding", value = "enabled", matchIfMissing = true)
public class HttpEncodingAutoConfiguration {
private final Encoding properties;
public HttpEncodingAutoConfiguration(ServerProperties properties) {
this.properties = properties.getServlet().getEncoding();
}
@Bean
@ConditionalOnMissingBean
public CharacterEncodingFilter characterEncodingFilter() {
CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
filter.setEncoding(this.properties.getCharset().name());
filter.setForceRequestEncoding(this.properties.shouldForce(Encoding.Type.REQUEST));
filter.setForceResponseEncoding(this.properties.shouldForce(Encoding.Type.RESPONSE));
return filter;
}
@Bean
public LocaleCharsetMappingsCustomizer localeCharsetMappingsCustomizer() {
return new LocaleCharsetMappingsCustomizer(this.properties);
}
static class LocaleCharsetMappingsCustomizer
implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>, Ordered {
private final Encoding properties;
LocaleCharsetMappingsCustomizer(Encoding properties) {
this.properties = properties;
}
@Override
public void customize(ConfigurableServletWebServerFactory factory) {
if (this.properties.getMapping() != null) {
factory.setLocaleCharsetMappings(this.properties.getMapping());
}
}
@Override
public int getOrder() {
return 0;
}
}
}
@Configuration:表示这是一个配置类,以前编写的配置文件一样,也可以给容器中添加组件;
@EnableConfigurationProperties(xxx.class):启动指定类的ConfigurationProperties。这里指定启动ServerProperties.class,我们进入这个类,我们发现他类似javabean对象,里面只有变量及其get/set方法,但是我们发现他又个注解。
@ConfigurationProperties(prefix = “xxx”)这个注解的意思就是找到配置文件与本对象相的同字段的属性值注入进来。简单来说就是把resources目录下的application.properties中与prefix指定值一样的且要本对象有的下属属性注入进来到本对象中。
@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true)
public class ServerProperties {
...
}
说到这儿我们基本知道自动装配原理,也知道配置文件是怎么把数据注入到相应的类中了。我们继续向下看注解
@ConditionalOnWebApplication( type = Type.SERVLET):判断当前应用是否是web应用,如果是,当前配置类生效。
@ConditionalOnClass({CharacterEncodingFilter.class}):判断当前项目有没有这个类CharacterEncodingFilter;SpringMVC中进行乱码解决的过滤器;
@ConditionalOnProperty(prefix = “server.servlet.encoding”, value = “enabled”, matchIfMissing = true):判断配置文件中是否存在某个配置:spring.http.encoding.enabled;如果不存在,判断也是成立的。即使我们配置文件中不配置pring.http.encoding.enabled=true,也是默认生效的;
一句话总结 : 根据当前不同的条件判断,决定这个配置类是否生效! 一但这个配置类生效;这个配置类就会给容器中添加各种组件;这些组件的属性是从对应的properties类中获取的,这些类里面的每一个属性又是和配置文件绑定的;所有在配置文件中能配置的属性都是在xxxxProperties类中封装者‘;配置文件能配置什么就可以参照某个功能对应的这个属性类
流程图:
SpringBoot自动装配流程图
@Conditional
了解完自动装配的原理后,我们来关注一个细节问题 ,自动配置类必须在一定的条件下才能生效;
@Conditional派生注解(Spring注解版原生的@Conditional作用)
作用:必须是@Conditional指定的条件成立,才给容器中添加组件,配置配里面的所有内容才生效;
总结
springboot自动装配其实就找到xxxAutoConfiguration类,XXXAutoConfiguration这个类其实就是一个配置类,他把需要的类都加载的容器中,然后通过@EnableConfigurationProperties(xxxProperties.class)获得配置属性需要的值,但是还要进入这个类通过@ConfigurationProperties(prefix = “xxx”)来把配置文件中的配置导入进来。