0%

springboot主程序

springboot主程序

使用过springboot的都应该知道,springboot的主程序类上是由一个注解@SpringBootApplication的,这个注解表明了这个项目是一个springboot项目,也标注了这个类是springboot的主配置类

但是这个注解里的内容其实是很多的

1
2
3
4
5
6
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

下面就分别介绍一下这里边的注解

@SpringBootConfiguration

这个注解是用来标注springboot的配置类的,看一下该注解的组成就知道了,是@Configuration注解,spring底层就是来以@Configuration注解标注的类作为配置类的

1
2
3
4
@Configuration
public @interface SpringBootConfiguration {

}

@EnableAutoConfiguration

这个注解是用来开启自动配置功能的,用来告诉springboot开启自动配置功能,看一下这个注解的构成

看到了@Import注解就知道了,用@Import注解来进行组件导入,还是原来spring的那一套,使用selector选择器来进行操作

1
2
3
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {

这里主要加载了两个文件META-INF/spring-autoconfigure-metadata.properties和META-INF/spring.factories

这个EnableAutoConfigurationImportSelector的作用是将META-INF/spring.factories文件中写的org.springframework.boot.autoconfigure.EnableAutoConfiguration对应的所有的xxxAutoConfiguration注册进来

接下来看一下@AutoConfigurationPackage里是什么,也是一个@Import注解,使用Registrar注册器来进行组件注册

1
2
3
4
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {

}

这个AutoConfigurationPackages.Registrar的作用是将被@SpringBootApplication标注的主配置类所在的包以及其子包中的类扫描进spring容器

@ComponentScan

这个注解是用来进行组件扫描的,在spring中就已经存在了,可以自动发现和装配bean

自动配置报告

可以在配置文件中配置来查看哪些自动配置生效了,哪些没生效

1
debug: true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
=========================
AUTO-CONFIGURATION REPORT
=========================
Positive matches: (生效的自动配置)
-----------------

DispatcherServletAutoConfiguration matched:
- @ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
- @ConditionalOnWebApplication (required) found 'session' scope (OnWebApplicationCondition)

Negative matches:(没生效的自动配置,以及哪些条件没满足)
-----------------

ActiveMQAutoConfiguration:
Did not match:
- @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition)

欢迎关注我的其它发布渠道