首先我们分析的就是入口类Application
的启动注解@SpringBootApplication
,进入源码:
@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 {
....
@SpringBootApplication
是一个复合注解,包括
@ComponentScan
@SpringBootConfiguration
@EnableAutoConfiguration
@SpringBootConfiguration
继承自@Configuration
,二者功能也一致,标注当前类是配置类,并会将当前类内声明的一个或多个以@Bean
注解标记的方法的实例纳入到spring
容器中,并且实例名就是方法名。加了这个注解的类会被自动加载到ioc容器中!
@EnableAutoConfiguration
的作用启动自动的配置,@EnableAutoConfiguration
注解的意思就是Springboot
根据你添加的jar包来配置你项目的默认配置,比如根据spring-boot-starter-web
,来判断你的项目是否需要添加了webmvc
和tomcat
,就会自动的帮你配置web项目中所需要的默认配置。@SpringBootApplication能自动的配置一些信息,主要依赖与这个注解!它里面有一个@AutoConfigrationPackage,该注解可以自动将包放到扫描器里面,它找到@SpringBootApplication所在类的,这样就会将该包和它所有的子包全部纳入spring容器!如,主包是hu.ren.wei ,子包为:hu.ren.wei.xxxx@ComponentScan
,扫描当前包及其子包下被@Component
,@Controller
,@Service
,@Repository
注解标记的类并纳入到spring容器中进行管理。是以前的<context:component-scan>
(以前使用在xml中使用的标签,用来扫描包配置的平行支持)。所以本demo中的User为何会被spring
容器管理。
链接:https://www.jianshu.com/p/4e1cab2d8431