签名:但行好事,莫问前程。
文章目录
前言
@SpringBootApplication的分析
@SpringBootApplication
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
@SpringBootApplication标注在程序的主启动类上面,他由三个注解组成:@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {}
@SpringBootConfiguration
@SpringBootConfiguration表明该类是SpringBoot的一个核心配置类,他的底层注解是:@Configuration
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
@Indexed
public @interface SpringBootConfiguration {}
@Configuration
@Configuration:标注在类上面,告诉springboot这是一个配置类。
@Configuration
public class MyConfig {
}
@Bean:给容器中注册组件,以方法名作为组件id,返回类型就是组件类型,返回的值是容器中的实例(默认是单实例)。
@Bean
public User user (){
return new User("yangcunle", 18);
}
从容器中获取user组件:
@SpringBootApplication
@Slf4j
public class MainApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
User user = run.getBean("user", User.class);
log.info(user.toString());
}
}
@Configuration 中 boolean proxyBeanMethods() default true; (代理bean的方法,默认true)
当我们多次获取组件的时候,获取的是同一个实例。
当我们把proxyBeanMethods 改为 false 时,再运行代码:
@Configuration(proxyBeanMethods = false)
public class MyConfig {
@Bean
public User user (){
return new User("yangcunle", 18);
}
}
此时从容其中获取的就不是同一个实例了。
@EnableAutoConfiguration
@EnableAutoConfiguration是启用自动配置注解。由两个注解组成:@AutoConfigurationPackage、@Import
@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点击进入源码,发现有一个方法批量注册组件。
将指定包(com.yangcunle.boot)下面的所有组件注册进来。
@Import(AutoConfigurationImportSelector.class)
@Import(AutoConfigurationImportSelector.class):给容器中批量导入了哪些包?
点击进入AutoConfigurationImportSelector.class查看:
public String[] selectImports(AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return NO_IMPORTS;
}
// 使用该方法给容器中批量导入组件
AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(annotationMetadata);
return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
getAutoConfigurationEntry(annotationMetadata) 获取所有配置结合
protected AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return EMPTY_ENTRY;
}
AnnotationAttributes attributes = getAttributes(annotationMetadata);
List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
configurations = removeDuplicates(configurations);
Set<String> exclusions = getExclusions(annotationMetadata, attributes);
checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
configurations = getConfigurationClassFilter().filter(configurations);
fireAutoConfigurationImportEvents(configurations, exclusions);
return new AutoConfigurationEntry(configurations, exclusions);
}
获取所有需要导入到容器中的配置类
List configurations =getCandidateConfigurations(annotationMetadata, attributes);
XXXtAutoConfiguration (啥啥啥自动配置类)
这里以RabbitAutoConfiguration为例:
@ConditionalOnClass({ RabbitTemplate.class, Channel.class }) 按条件加载
@Bean
@ConditionalOnMissingBean // 如果这个组件不在容器中,就往容器中注册这个组件
RabbitConnectionFactoryBeanConfigurer rabbitConnectionFactoryBeanConfigurer(RabbitProperties properties,
ResourceLoader resourceLoader, ObjectProvider<CredentialsProvider> credentialsProvider,
ObjectProvider<CredentialsRefreshService> credentialsRefreshService) {
RabbitConnectionFactoryBeanConfigurer configurer = new RabbitConnectionFactoryBeanConfigurer(resourceLoader,
properties);
configurer.setCredentialsProvider(credentialsProvider.getIfUnique());
configurer.setCredentialsRefreshService(credentialsRefreshService.getIfUnique());
return configurer;
}
再看看Redis的自动配置类:
按照条件加载规则,按需加载组件。
@ComponentScan
@ComponentScan:扫描那些包的注解。
自动配置流程总结
- SpringBoot优先加载所有的自动配置类(xxxAutoConfiguration)
- 每个自动配置类按条件进行生效,默认都会绑定配置文件指定的值(@EnableConfigurationProperties(xxxProperties.class))
- xxxProperties.class通过@ConfigurationProperties(prefix = “spring.xxx”)与application.properties配置文件绑定
- 生效的配置类就会给容器中装配对应的组件
- 定制化配置
- 用@Bean注解去替换底层的组件
- 去application.properties配置文件里面修改指定的值
我们再以我们熟知的 spring-boot-starter-web 里面的 DispatcherServletAutoConfiguration 完整看一遍
1、org.springframework.boot.autoconfigure.web.servlet 包下面的 DispatcherServletAutoConfiguration(xxxAutoConfiguration)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) // 配置文件的生效顺序
@AutoConfiguration(after = ServletWebServerFactoryAutoConfiguration.class) // 在ServletWebServerFactoryAutoConfiguration配置文件生效后生效
@ConditionalOnWebApplication(type = Type.SERVLET) // WebApplication的类型是SERVLET
@ConditionalOnClass(DispatcherServlet.class)// 添加判断:DispatcherServlet.class引入才生效
public class DispatcherServletAutoConfiguration {}
2、因为我们引入了spring-boot-starter-web依赖,所以以上条件都满足,接着往下看
@Configuration(proxyBeanMethods = false) // 不启动代理
@Conditional(DefaultDispatcherServletCondition.class) // 满足DefaultDispatcherServletCondition里面的条件
@ConditionalOnClass(ServletRegistration.class) // 是否存在ServletRegistration类
@EnableConfigurationProperties(WebMvcProperties.class) // 绑定WebMvcProperties配置文件(xxxProperties.class)
protected static class DispatcherServletConfiguration {
// 给容器中注册组件dispatcherServlet
@Bean(name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
public DispatcherServlet dispatcherServlet(WebMvcProperties webMvcProperties) {
DispatcherServlet dispatcherServlet = new DispatcherServlet();
// 一系列的默认配置都是从WebMvcProperties配置文件类里面读取的
dispatcherServlet.setDispatchOptionsRequest(webMvcProperties.isDispatchOptionsRequest());
dispatcherServlet.setDispatchTraceRequest(webMvcProperties.isDispatchTraceRequest());
dispatcherServlet.setThrowExceptionIfNoHandlerFound(webMvcProperties.isThrowExceptionIfNoHandlerFound());
dispatcherServlet.setPublishEvents(webMvcProperties.isPublishRequestHandledEvents());
dispatcherServlet.setEnableLoggingRequestDetails(webMvcProperties.isLogRequestDetails());
// 配置好了基本的参数之后,返回dispatcherServlet对象
return dispatcherServlet;
}
// 给容器中注册文件上传组件multipartResolver
@Bean
@ConditionalOnBean(MultipartResolver.class) // 系统中有没有MultipartResolver这个bean
@ConditionalOnMissingBean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME) // 有没有不叫这个名字“MULTIPART_RESOLVER_BEAN_NAME”的DispatcherServlet类型的bean
public MultipartResolver multipartResolver(MultipartResolver resolver) {
// Detect if the user has created a MultipartResolver but named it incorrectly
// 把用户自定义的,不叫“MULTIPART_RESOLVER_BEAN_NAME”的bean注册到容器(已用户自定义的bean优先)
return resolver;
}
}
3、细看一下 @EnableConfigurationProperties(WebMvcProperties.class)
// 通过@ConfigurationProperties注解绑定前缀为:"spring.mvc"的配置文件,并且每个属性都有一个默认值
@ConfigurationProperties(prefix = "spring.mvc")
public class WebMvcProperties {
/**
* Formatting strategy for message codes. For instance, 'PREFIX_ERROR_CODE'.
*/
private DefaultMessageCodesResolver.Format messageCodesResolverFormat;
private final Format format = new Format();
/**
* Whether to dispatch TRACE requests to the FrameworkServlet doService method.
*/
private boolean dispatchTraceRequest = false;
/**
* Whether to dispatch OPTIONS requests to the FrameworkServlet doService method.
*/
private boolean dispatchOptionsRequest = true;
/**
* Whether the content of the "default" model should be ignored during redirect
* scenarios.
*/
private boolean ignoreDefaultModelOnRedirect = true;
/**
* Whether to publish a ServletRequestHandledEvent at the end of each request.
*/
private boolean publishRequestHandledEvents = true;
/**
* Whether a "NoHandlerFoundException" should be thrown if no Handler was found to
* process a request.
*/
private boolean throwExceptionIfNoHandlerFound = false;
/**
* Whether logging of (potentially sensitive) request details at DEBUG and TRACE level
* is allowed.
*/
private boolean logRequestDetails;
/**
* Whether to enable warn logging of exceptions resolved by a
* "HandlerExceptionResolver", except for "DefaultHandlerExceptionResolver".
*/
private boolean logResolvedException = false;
/**
* Path pattern used for static resources.
*/
private String staticPathPattern = "/**";
private final Async async = new Async();
private final Servlet servlet = new Servlet();
private final View view = new View();
private final Contentnegotiation contentnegotiation = new Contentnegotiation();
private final Pathmatch pathmatch = new Pathmatch();
可以在配置文件中修改配置文件的默认值,达到定制化修改组件的需求。
总结
博客主要记录了@SpringBootApplication的分析,有啥错误或不足地方请指正,如果对你有所帮助,请一键三连。