当前位置: 首页 > news >正文

springboot系列--自动配置原理

一、容器功能

一、组件添加功能

一、@Configuration

@Configuration有两种模式,Full模式与Lite模式。

1、配置 类组件之间无依赖关系用Lite模式加速容器启动过程,减少判断

2、配置类组件之间有依赖关系,方法会被调用得到之前单实例组件,用Full模式

/*** 1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的* 2、配置类本身也是组件* 3、proxyBeanMethods:代理bean的方法*      Full(proxyBeanMethods = true)、【保证每个@Bean方法被调用多少次返回的组件都是单实例的】*      Lite(proxyBeanMethods = false)【每个@Bean方法被调用多少次返回的组件都是新创建的】*      组件依赖必须使用Full模式默认。其他默认是否Lite模式****/
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
public class MyConfig {/*** Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象* @return*/@Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例public User user01(){User zhangsan = new User("zhangsan", 18);//user组件依赖了Pet组件zhangsan.setPet(tomcatPet());return zhangsan;}@Bean("tom")public Pet tomcatPet(){return new Pet("tomcat");}
}

 二、@Bean、@Component、@Controller、@Service、@Repository都可以实现往容器中注入添加组件

三、@ComponentScan、@Import

 * 4、@Import({User.class, DBHelper.class})
 *      给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名
 *
 *
 *
 */

@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
public class MyConfig {
}

四、@Conditional条件装配

 满足Conditional指定的条件,则进行组件注入

1、@ConditionalOnBean:存在指定的bean,则注入

2、@ConditionalOnMissingBean:不存在指定的bean,则注入

3、@ConditionalOnClass:存在指定类,则注入

4、@ConditionalOnMissingClass:不存在指定的类,则注入

二、原生配置文件导入

@ImportResource("classpath:beans.xml")

导入指定的bean.xml文件中的配置进入容器中,形成bean

三、配置绑定

使用Java读取到properties文件中的内容(实际项目中一般会把这里的配置放到nacos中),并且把它封装到JavaBean中,以供随时使用:

public class getProperties {public static void main(String[] args) throws FileNotFoundException, IOException {Properties pps = new Properties();pps.load(new FileInputStream("a.properties"));Enumeration enum1 = pps.propertyNames();//得到配置文件的名字while(enum1.hasMoreElements()) {String strKey = (String) enum1.nextElement();String strValue = pps.getProperty(strKey);System.out.println(strKey + "=" + strValue);//封装到JavaBean。}}}

 一、@ConfigurationProperties

这个注解只是单纯的进行配置绑定,并还没有注入容器,所以如果还想通过spring的注解从容器中获取对象,就需要使用@Component或者其他一些注入容器中的注解,把@ConfigurationProperties修饰的对象也一起注入容器中。

/*** 只有在容器中的组件,才会拥有SpringBoot提供的强大功能*/
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {private String brand;private Integer price;public String getBrand() {return brand;}public void setBrand(String brand) {this.brand = brand;}public Integer getPrice() {return price;}public void setPrice(Integer price) {this.price = price;}@Overridepublic String toString() {return "Car{" +"brand='" + brand + '\'' +", price=" + price +'}';}
}

二、@EnableConfigurationProperties + @ConfigurationProperties

@EnableConfigurationProperties开启指定类的绑定功能,且自动注入到容器中去,也就是那个类使用了@ConfigurationProperties修饰,通过@EnableConfigurationProperties指定那个类,就可以在不使用@Component的情况下注入进容器

@EnableConfigurationProperties(Car.class)
//1、开启Car配置绑定功能
//2、把这个Car这个组件自动注册到容器中
public class MyConfig {
}

二、自动配置原理

一、引导加载自动配置

自动配置主要是同过@SpringBootApplication这个类注解实现的,这个注解是一个合成注解,里面由多个注解组成。

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })

一、 @SpringBootConfiguration

使用@Configuration修饰这个注解。代表当前这个注解是一个配置类

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {}

二、@ComponentScan

指定扫描哪些,Spring注解;

@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })excludeFilters :排除指定的组件
FilterType.CUSTOM:按照自定义规则排除
TypeExcludeFilter.class:自定义规则组件

 三、@EnableAutoConfiguration

@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {}

一、@AutoConfigurationPackage

自动导包配置注解,里面是@Import(AutoConfigurationPackages.Registrar.class)

1、AutoConfigurationPackages.Registrar.class

	@Overridepublic void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {register(registry, new PackageImport(metadata).getPackageName());}metadata:注解元信息,也就是这个注解修饰的类的全路径类名
register:扫描注解所在的类的包下的所有组件,并注册进容器,也就是SpringAnnotateApplication所在的包。所以springboot,默认自动导入SpringAnnotateApplication所在的包下的所有组件。

	public static void register(BeanDefinitionRegistry registry, String... packageNames) {// BEAN:AutoConfigurationPackages.class.getName()// 判断容器中是否有自动配置类,如果该bean已经注册,则将要注册包名称添加进去if (registry.containsBeanDefinition(BEAN)) {BeanDefinition beanDefinition = registry.getBeanDefinition(BEAN);ConstructorArgumentValues constructorArguments = beanDefinition.getConstructorArgumentValues();constructorArguments.addIndexedArgumentValue(0, addBasePackages(constructorArguments, packageNames));}else {//  //如果该bean尚未注册,则注册该bean,参数中提供的包名称会被设置到bean定义中去GenericBeanDefinition beanDefinition = new GenericBeanDefinition();// 注册的是BasePackages这个类beanDefinition.setBeanClass(BasePackages.class);// 这是他的参数beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, packageNames);beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);registry.registerBeanDefinition(BEAN, beanDefinition);}}

AutoConfigurationPackages.Registrar这个类就干一个事,注册一个Bean,这个Bean就是org.springframework.boot.autoconfigure.AutoConfigurationPackages.BasePackages,它有一个参数,这个参数是使用了@AutoConfigurationPackage这个注解的类所在的包路径,保存自动配置类以供之后的使用.

二、@Import({AutoConfigurationImportSelector.class}

主要是AutoConfigurationImportSelector类中getAutoConfigurationEntry方法给容器进行批量导入组件。

1、进入getAutoConfigurationEntry方法,找到List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);这行代码,这里就把指定路径下文件中的配置类加载进入容器了。

2、进入getCandidateConfigurations,只有一行List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());是主要代码,从这里进入可以看到具体加载逻辑

 

3、loadSpringFactories(@Nullable ClassLoader classLoader)方法是主要的加载逻辑

    private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
// 先从缓存中获取配置文件MultiValueMap<String, String> result = (MultiValueMap)cache.get(classLoader);if (result != null) {return result;} else {// 如果没有从指定classLoader,则默认加载系统下所有META-INF/spring.factories位置中的文件try {Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");MultiValueMap<String, String> result = new LinkedMultiValueMap();// 循环处理,然后放入缓存while(urls.hasMoreElements()) {URL url = (URL)urls.nextElement();UrlResource resource = new UrlResource(url);Properties properties = PropertiesLoaderUtils.loadProperties(resource);Iterator var6 = properties.entrySet().iterator();while(var6.hasNext()) {Map.Entry<?, ?> entry = (Map.Entry)var6.next();String factoryTypeName = ((String)entry.getKey()).trim();String[] var9 = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());int var10 = var9.length;for(int var11 = 0; var11 < var10; ++var11) {String factoryImplementationName = var9[var11];result.add(factoryTypeName, factoryImplementationName.trim());}}}cache.put(classLoader, result);return result;} catch (IOException var13) {throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var13);}}}

spring-boot-autoconfigure这个包里面也有META-INF/spring.factories文件,文件里面写死了spring-boot启动就要给容器中加载的所有配置类。

 虽然springboot启动时,就默认加载META-INF/spring.factories下的所有配置文件,但是这些配置文件并不是所有都会启动,他们只会按条件装配,只有符合某些条件,才会开启。以下是几个springboot底层按条件开启配置的栗子:

1、springboot底层给容器中加入了文件上传解析器

        @Bean
        @ConditionalOnBean(MultipartResolver.class)  //容器中有这个类型组件
        @ConditionalOnMissingBean(name = DispatcherServlet.) //容器中没有这个名字 multipartResolver 的组件
        public MultipartResolver multipartResolver(MultipartResolver resolver) {
            //给@Bean标注的方法传入了对象参数,这个参数的值就会从容器中找。
            //SpringMVC multipartResolver。防止有些用户配置的文件上传解析器不符合规范
            // 有些用户可能配置了MultipartResolver这个类型的组件,但是组件名字不规范
            return resolver;
        }

2、优先使用用户配置

@Bean
@ConditionalOnMissingBean // 如果容器中没有CharacterEncodingFilter 这个bean才开启,相当于优先使用用户的,用户没有会配置,将会开启这个兜底
public CharacterEncodingFilter characterEncodingFilter() {CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();filter.setEncoding(this.properties.getCharset().name());filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.REQUEST));filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.RESPONSE));return filter;
}

三、总结 

1、SpringBoot启动时先加载META-INF/spring.factories下所有的自动配置类 xxxxxAutoConfiguration

2、每个自动配置类按照条件进行生效,默认都会绑定配置文件指定的值。xxxxProperties里面拿。xxxProperties和配置文件进行了绑定

3、生效的配置类就会给容器中装配很多组件

4、只要容器中有这些组件,相当于这些功能就有了

5、用户可以自己定制化配置,有两种方式:

         a、直接自己写配置类使用@Bean替换底层的组件

         b、用户去看这个组件是获取的配置文件什么值就去修改。

6、如果想要查看容器是否开启了对应组件,有两种方式

        a、在启动类中获取容器中的bean,查看容器中是否成功加载。

        b、还有一种就是在配置文件中配置debug=true开启自动配置报告。Negative(不生效)\Positive(生效),直接配置没有前缀。

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • QT 联合opencv 易错点
  • 自动驾驶相关的理论基础
  • C语言-数据结构 无向图迪杰斯特拉算法(Dijkstra)邻接矩阵存储
  • vscode 使用git bash,路径分隔符缺少问题
  • 苍穹外卖学习笔记(三)
  • 深度学习驱动下的字符识别:挑战与创新
  • Vue Router 入门指南:基础配置、路由守卫与动态路由
  • 关于武汉芯景科技有限公司的IIC缓冲器芯片XJ4307开发指南(兼容LTC4307)
  • LabVIEW软件,如何检测连接到的设备?
  • 3.记:Android EditText接收扫码枪输入数据丢失问题
  • 828华为云征文|华为云Flexus X实例docker部署MinIO对象存储系统obs
  • 【机器人工具箱Robotics Toolbox开发笔记(一)】Matlab机器人工具箱简介
  • 如何在Word中插入复选框
  • Linux内核 -- CGROUP子系统之内存控制组 mem_cgroup_charge函数
  • idea中配置Translation插件完成翻译功能
  • [译]如何构建服务器端web组件,为何要构建?
  • C语言笔记(第一章:C语言编程)
  • JS笔记四:作用域、变量(函数)提升
  • JS变量作用域
  • Netty 框架总结「ChannelHandler 及 EventLoop」
  • Promise面试题,控制异步流程
  • Travix是如何部署应用程序到Kubernetes上的
  • web标准化(下)
  • 大数据与云计算学习:数据分析(二)
  • 前端技术周刊 2019-02-11 Serverless
  • 如何学习JavaEE,项目又该如何做?
  • 深入浏览器事件循环的本质
  • 在weex里面使用chart图表
  • ​二进制运算符:(与运算)、|(或运算)、~(取反运算)、^(异或运算)、位移运算符​
  • #HarmonyOS:Web组件的使用
  • ( )的作用是将计算机中的信息传送给用户,计算机应用基础 吉大15春学期《计算机应用基础》在线作业二及答案...
  • (13)[Xamarin.Android] 不同分辨率下的图片使用概论
  • (4)Elastix图像配准:3D图像
  • (LLM) 很笨
  • (windows2012共享文件夹和防火墙设置
  • (附源码)spring boot智能服药提醒app 毕业设计 102151
  • (十七)Flink 容错机制
  • (四)js前端开发中设计模式之工厂方法模式
  • (图)IntelliTrace Tools 跟踪云端程序
  • (学习日记)2024.03.12:UCOSIII第十四节:时基列表
  • (转) SpringBoot:使用spring-boot-devtools进行热部署以及不生效的问题解决
  • *算法训练(leetcode)第四十七天 | 并查集理论基础、107. 寻找存在的路径
  • .NET Core 成都线下面基会拉开序幕
  • .net core 管理用户机密
  • .net dataexcel 脚本公式 函数源码
  • .NET HttpWebRequest、WebClient、HttpClient
  • .NET 材料检测系统崩溃分析
  • .NET 程序如何获取图片的宽高(框架自带多种方法的不同性能)
  • .NET 同步与异步 之 原子操作和自旋锁(Interlocked、SpinLock)(九)
  • .NET+WPF 桌面快速启动工具 GeekDesk
  • .NET单元测试
  • .NET导入Excel数据
  • .NET项目中存在多个web.config文件时的加载顺序
  • .NET之C#编程:懒汉模式的终结,单例模式的正确打开方式
  • .NET周刊【7月第4期 2024-07-28】