全国建设部网站证书查询,怎么做网站编辑,怎么用织梦搭建网站,外贸网站批量收录一、前言
在SpringBoot项目中启动类必须加一个注解SpringBootApplication#xff0c;今天我们来剖析SpringBootApplication这个注解到底做了些什么。
二、SpringBootApplication简单分析
进入SpringBootApplication源代码如下#xff1a; 可以看出SpringBootApplication是…一、前言
在SpringBoot项目中启动类必须加一个注解SpringBootApplication今天我们来剖析SpringBootApplication这个注解到底做了些什么。
二、SpringBootApplication简单分析
进入SpringBootApplication源代码如下 可以看出SpringBootApplication是一个复合注解里边主要组合了
SpringBootConfiguration、CompoentScan、EnableAutoConfiguration这三个注解。
1、SpringBootConfiguration
SpringBootConfiguration组合了Configuration它是用来声明当前类是一个配置类被注解类的内部包含一个或多个Bean注解的方法用于替换xml配置定义这些方法将被
AnnotationConfigApplicationContext类进行扫描注入Spring容器中。
简单例子直接使用Configuration和Bean来注入容器。
1创建一个普通项目引入依赖
implementation org.springframework:spring-context:5.1.9.RELEASE
2创建一个Configuration类 定义Bean对象。 Configuration Bean相当于
beans bean iduser classorg.example.User/bean
/beans
的定义。
3测试类
通过AnnotationConfigApplicationContext将定义的Bean加载到Spring IOC容器中。 输出如下
注AnnotationConfigApplicationContext最终会调用BeanDefinitionReaderUtils.registerBeanDefinition进行注入。
2、CompoentScan
定义一个Spring Bean是在类上加上注解Service、Controller、Compent就可以而Spring是通过扫描CompoentScan指定包下所有加了注解的类如果不写它只会加载启动类所在的包及下级包。
简单例子
1、在包com.example.sacn新建一个类 2、在包com.example.app下创建一个启动类 3、输出找不到对应的Bean (4)、启动类加注解运行正常
ComponentScan(com.example.scan)
具体源代码在
ComponentScanAnnotationParser.parse()会将所有标注了Component并匹配ComponentScan规则的类都注册到容器中去Controller、Service、Responsitory都标有Conpoment注解。
3、EnableAutoConfiguration
EnableAutoConfiguration是SpringBoot实现自动化配置的核心注解通过这个注解把Spring应用所需的bean注入到容器中。 EnableAutoConfiguration通过Import注入一个ImportSelector的实现类AutoConfigurationImportSelector这个类根据我们的配置动态加载所需要的Bean。
核心代码如下 注主要完成过滤筛选需要注入的类。
催着吃钣了