SpringBoot基础入门--了解自动配置原理

1、SpringBoot特点

1.1、依赖管理

Springboot 的每个版本都提供了它所支持的经过精心策划的依赖项列表。实际上,您不需要为构建配置中的任何依赖项提供一个版本,因为 Spring Boot 为您管理这些依赖项。当您升级 Spring Boot 本身时,这些依赖关系也会以一致的方式升级。

在pom.xml文件添加SpringBoot的父项目依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.3</version>
    </parent>

父项目的父项目,几乎声明了所有开发中常用的依赖的版本号,自动版本仲裁机制

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.5.3</version>
  </parent>

1.2、自动配置

每一个XxxxAutoConfiguration自动配置类都是在某些条件之下才会生效的,这些条件的限制在Spring Boot中以注解的形式体现,常见的条件注解有如下几项:

@ConditionalOnBean:当容器里有指定的bean的条件下。

@ConditionalOnMissingBean:当容器里不存在指定bean的条件下。

@ConditionalOnClass:当类路径下有指定类的条件下。

@ConditionalOnMissingClass:当类路径下不存在指定类的条件下。

@ConditionalOnProperty:指定的属性是否有指定的值,比如@ConditionalOnProperties(prefix=”xxx.xxx”, value=”enable”, matchIfMissing=true),代表当xxx.xxx为enable时条件的布尔值为true,如果没有设置的情况下也为true。

1.2.1、定位主要应用程序类

我们通常建议您将主应用程序类定位在根包中,位于其他类之上。@ springbootapplication 注释通常放在您的主类上,它隐式地为某些项定义一个基本的“搜索包”
在这里插入图片描述
Java 文件将声明 main 方法,以及基本的@springbootapplication,如下所示:

/*
    主程序类
    @SpringBootApplication :说明这是一个SpringBoot应用 :  启动类下的所有资源被导入
 */

@SpringBootApplication
public class MainApplication {

    //将SpringBoot应用启动
    public static void main(String[] args){
        //1、返回IOC容器
        ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class);
}

主程序所在包及其下面的所有子包里面的组件都会被默认扫描进来
无需以前的包扫描配置
想要改变扫描路径,@SpringBootApplication(scanBasePackages=“com.shiqi”)
或者@ComponentScan 指定扫描路径

@SpringBootApplication
等同于
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.shiqi.boot")

1.3丶配置绑定

@ConfigurationProperties

只有在容器中的组件,才会拥有SpringBoot提供的强大功能

2、容器功能

2.1、初步了解配置组件

@Configuration :配置
@Bean
@Componet :组件
@Repository :持久层标注
@Service :业务层标注
@Controller : 控制层标注
@ComponentScan :组件扫描
@Import :添加
@Conditional :条件装配
@ImportResource :导入文件

config包
MyConfig.java类

/**
 *  1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的
 *  2、配置类本身也是一个组件
 *  3、proxyBeanMethods:代理bean方法
 *      Full(proxyBeanMethods = true)
 *      Lite(proxyBeanMethods = false)
 *      用来解决组件依赖的问题
 *  注解的意思是proxyBeanMethods配置类是用来指定@Bean注解标注的方法是否使用代理,默认是true使用代理,直接从IOC容器之中取得对象;
 *  如果设置为false,也就是不使用注解,每次调用@Bean标注的方法获取到的对象和IOC容器中的都不一样,是一个新的对象,所以我们可以将此属性设置为false来提高性能;
 *
 *  Full模式与Lite模式
 *      配置类组件之间无依赖关系用Lite模式加速容器启动过程,减少判断
 *      配置类组件之间有依赖关系,方法会被调用得到之前单实例组件,用Full模式
 *
 *   4、@Import({Person.class}) 调用这个类的无参构造器,创建出组件类型的对象放在容器中
 *          给容器中自动创建出这个类型的组件  默认组件的名字就是全类名
 *
 *
 *   5、@@ImportResource("classpath:beans.xml") 导入Spring配置文件
 */

@Import({Person.class})
@ImportResource("classpath:beans.xml") //导入类路径下的beans.xml文件
@Configuration(proxyBeanMethods = false)  //告诉SpringBoot这是一个配置类 等同于之前的 配置类
//条件装配
@ConditionalOnBean(name = "user01") //意思是:这个配置类中存在user组件才生效,
public class MyConfig {

    /**
     * 外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例
     * @return
     */
    @Bean  //给容器中添加组件。以方法名作为组件的id。返回值类型,就是组件类型。 返回的值,就是组件在容器中的实例。
    public Person user(){
        return new Person("张三",3);
    }

    @Bean
    @ConditionalOnBean(name = "user") //存在user组件,pet组件才生效,可以将@ConditionalOnBean(name = "user")放在类上
    public Dog pet(){
        return  new Dog("小黄",3);
    }

    @ConditionalOnBean(name = "zhangsan") //存在zhangsan组件,dog组件才生效
    public Dog dog(){
        return  new Dog("小王",3);
    }

}

MainApplication.java类
测试的时候需要需将 注释:config包
MyConfig.java类@ConditionalOnBean(name = “user01”)
意思是:这个配置类中存在user组件才生效,因为文件中没有user01组件。

/*
    主程序类
    @SpringBootApplication :说明这是一个SpringBoot应用 :  启动类下的所有资源被导入
 */

@SpringBootApplication
public class MainApplication {

    //将SpringBoot应用启动
    public static void main(String[] args){
        //1、返回IOC容器
        ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class);

        2、查看容器里面的组件
        //String[] nameList = run.getBeanDefinitionNames();
        //for(String names : nameList){
        //    System.out.println(names);
        //}
        //
        3、从容器中获取组件
        //Person user = run.getBean("user", Person.class);
        //Person user1 = run.getBean("user", Person.class);
        //System.out.println("组件:" + (user == user1));
        //
        4、com.shiqi.boot.config.MyConfig$$EnhancerBySpringCGLIB$$9e0bfc6d@29a23c3d
        //MyConfig bean = run.getBean(MyConfig.class);
        //System.out.println(bean);
        //
        如果@Configuration(proxyBeanMethods = true)代理对象调用方法。SpringBoot总会检查这个组件是否在容器有
        保持组件单实例
        //Person user2 = bean.user();
        //Person user3 = bean.user();
        //
        //System.out.println(user2 == user3);
        //
        //
        5、获取组件
        //System.out.println("===========");
        //String[] beanNamesForType = run.getBeanNamesForType(Person.class);
        //for(String str : beanNamesForType){
        //    System.out.println(beanNamesForType);

        boolean pet = run.containsBean("pet");
        System.out.println("容器中是否存在pet组件:" + pet);

        boolean user4 = run.containsBean("user");
        System.out.println("容器中是否存在user组件:" + user4);

        boolean dog = run.containsBean("dog");
        System.out.println("容器中是否存在dog组件:" + dog);
        
        //@ImportResource("classpath:beans.xml") 测试
        boolean person01 = run.containsBean("person01");
        System.out.println("容器中是否存在person01:" + person01);
    }
}

beans.xml 在SpringBoot中不建议使用这个方法添加配置,
如果您必须使用基于 XML 的配置,我们建议您仍然从@configuration 类开始。然后可以使用@importresource 注释来加载 XML 配置文件。
类似于在:config包MyConfig.java类@ImportResource(“classpath:beans.xml”) //导入类路径下的beans.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


    <!--之前SpringXML配置的方式添加配置文件-->
    <bean id="person01" class="com.shiqi.boot.bean.Person">
        <property name="name" value="嘿嘿嘿"/>
        <property name="age" value="3"/>
    </bean>

    <bean id="dog01" class="com.shiqi.boot.bean.Dog">
        <property name="name" value="小黄"/>
        <property name="age" value="3"/>
    </bean>
</beans>

2.2、自动配置原理入门

在这里插入图片描述

2.2.1、引导加载自动配置类

@SpringBootApplication主要功能由@SpringBootCofiguration、@EnableAotoConfiguration、@ComponentScan组成

在这里插入图片描述

@SpringBootConfiguration

进入@SpringBootConfiguration注解,存在@Configuration

在这里插入图片描述

进入@ComponentScan(。。。)注解

在这里插入图片描述

进入@EnableAutoConfiguration注解

在这里插入图片描述

进入@AutoConfigurationPackage注解

在这里插入图片描述

进入@Import({AutoConfigurationImportSelector.class})

在这里插入图片描述
查看this.getAutoConfigurationEntry(annotationMetadata);方法
在这里插入图片描述
在这里插入图片描述

查看this.getCandidateConfigurations(annotationMetadata, attributes);方法
在这里插入图片描述

进入工厂类,public static List loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader)
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
简单流程:
1、利用getAutoConfigurationEntry(annotationMetadata);给容器中批量导入一些组件
2、调用List configurations = getCandidateConfigurations(annotationMetadata, attributes)获取到所有需要导入到容器中的配置类
3、利用工厂加载 Map<String, List> loadSpringFactories(@Nullable ClassLoader classLoader);得到所有的组件
4、从META-INF/spring.factories位置来加载一个文件。
默认扫描我们当前系统里面所有META-INF/spring.factories位置的文件
spring-boot-autoconfigure-2.5.3.jar包里面也有META-INF/spring.factories

简单的说
@EnableAutoConfigration 注解会导入一个自动配置选择器去扫描每个jar包的META-INF/xxxx.factories 这个文件,这个文件是一个key-value形式的配置文件,里面存放了这个jar包依赖的具体依赖的自动配置类。这些自动配置类又通过@EnableConfigurationProperties 注解支持通过xxxxProperties 读取application.properties/application.yml属性文件中我们配置的值。如果我们没有配置值,就使用默认值,这就是所谓约定>配置的具体落地点。

2.2.2、按照需求开启自动配置项

所有自动配置启动的时候默认全部加载。xxxxAutoConfiguration
按照条件装配规则(@Conditional),最终会按需配置。

判断是否生效:

例如aop
在这里插入图片描述
在这里插入图片描述

2.2.3、修改默认配置

SpringBoot默认会在底层配好所有的组件。但是如果用户自己配置了以用户的优先

总结:

  • 综上是对自动配置原理简单理解
  • SpringBoot先加载所有的自动配置类
  • 自动配置:按照每个配置类的条件进行判断,判断成功则生效,否则不生效 常用组件
    @ConditionalOnBean
    @ConditionalOnMissingBean
    @ConditionalOnClass。
    @ConditionalOnMissingClass
    @ConditionalOnProperty@ConditionalOnProperties(prefix=”xxx.xxx”, value=”enable”, matchIfMissing=true)
    默认都会绑定配置文件的值,在xxxproperties里面的值,xxxproperties和配置文件进行了绑定。
  • 生效的配置类,会给容器提供很多的组件
  • 只要存在这些组件,功能就会存在
  • 优先使用自己配置的组件 @Bean自建 或 直接修改xxxproperties里面的值
    - 从xxxAutoConfiguration导入,把好多组件导入进去,再从xxxproperties里面获取值,xxxproperties和application.properties或application.yaml进行绑定,在application.properties或application.yaml里修改
    查文档修改或 查看底层源码修改
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值