spring boot自动配置

news2024/9/29 5:34:32

         Spring自动配置是Spring框架的一个核心特性,它允许开发者通过在类路径下的配置类发现bean,而无需在应用程序中显式地进行bean的声明。Spring Boot利用这一特性,通过starter依赖的机制和@EnableAutoConfiguration注解,帮助开发者快速地配置和启动Spring应用。

一,@Conditional

条件判断

使用方法
  • 自定义条件类

需要实现org.springframework.context.annotation.Condition接口或继承org.springframework.context.annotation.Condition的某个实现类(如OnPropertyCondition、OnBeanCondition等)。 实现Condition接口需要覆盖matches(ConditionContext, AnnotatedTypeMetadata)方法,这个方法会返回一个布尔值,表示是否满足条件。

  • 在@Bean方法或@Configuration类上使用@Conditional

可以将自定义的条件类作为@Conditional的值,或者直接使用Spring提供的条件注解(如@ConditionalOnProperty、@ConditionalOnBean等)。

源码

案例

在 Spring 的 IOC 容器中有一个 User 的 Bean,现要求:

1. 导入Jedis坐标后,加载该Bean,没导入,则不加载。

创建User配置类
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {
    Class<? extends Condition>[] value();
}
@Configuration
public class UserConfig {

    //@Conditional中的ClassCondition.class的matches方法,返回true执行以下代码,否则反之
    @Bean
    @Conditional(value= ClassCondition.class)
    public User user(){
        return new User();
    }
}
Condition 条件判断类
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        //1.需求: 导入Jedis坐标后创建Bean
        //思路:判断redis.clients.jedis.Jedis.class文件是否存在

        boolean flag = true;
        try {
            Class<?> cls = Class.forName("redis.clients.jedis.Jedis");
        } catch (ClassNotFoundException e) {
            flag = false;
        }
        return flag;

    }
测试
 public static void main(String[] args) {

        //启动SpringBoot的应用,返回Spring的IOC容器
        ConfigurableApplicationContext context =  SpringApplication.run(SpringbootCondition01Application.class, args);
        //获取Bean,redisTemplate
        //情况1 没有添加坐标前,发现为空
        //情况2 有添加坐标前,发现有对象
//        Object redisTemplate = context.getBean("redisTemplate");
//        System.out.println(redisTemplate);

        /********************案例1********************/
        Object user = context.getBean("user");
        System.out.println(user);


    }
需求2

在 Spring 的 IOC 容器中有一个 User 的 Bean,现要求:

将类的判断定义为动态的。判断哪个字节码文件存在可以动态指定

实现步骤:

  • 不使用@Conditional(ClassCondition.class)注解
  • 自定义注解@ConditionOnClass,因为他和之前@Conditional注解功能一直,所以直接复制
  • 编写ClassCondition中的matches方法

@Conditional(ClassCondition.class)注解不支持动态改变所以要自定义注解

创建ConditionOnClass注解
@Target({ElementType.TYPE, ElementType.METHOD})//可以修饰在类与方法上
@Retention(RetentionPolicy.RUNTIME)//注解生效节点runtime
@Documented//生成文档
@Conditional(value=ClassCondition.class)
public @interface ConditionOnClass {
    String[] value();//设置此注解的属性redis.clients.jedis.Jedis
}
ClassCondition类
//2.需求: 导入通过注解属性值value指定坐标后创建Bean
        //获取注解属性值  value

        Map<String, Object> map = metadata.getAnnotationAttributes(ConditionOnClass.class.getName());
        System.out.println(map);
        String[] value = (String[]) map.get("value");

        boolean flag = true;
        try {
            for (String className : value) {
                Class<?> cls = Class.forName(className);
            }
        } catch (ClassNotFoundException e) {
            flag = false;
        }
        return flag;
user配置类
@Configuration
public class UserConfig {

    //情况1
    @Bean
//    @Conditional(ClassCondition.class)
//    @ConditionOnClass(value="redis.clients.jedis.Jedis")
    @ConditionOnClass(value={"com.alibaba.fastjson.JSON","redis.clients.jedis.Jedis"})
    public User user(){
        return new User();
    }

    //情况2
    @Bean
    //当容器中有一个key=k1且value=v1的时候user2才会注入
    //在application.properties文件中添加k1=v1
    @ConditionalOnProperty(name = "k1",havingValue = "v1")
    public User user2(){
        return new User();
    }
}
Condition – 小结

自定义条件:

① 定义条件类:自定义类实现Condition接口,重写 matches 方法,在 matches 方法中进行逻辑判 断,返回

        boolean值 。 matches 方法两个参数:

                • context:上下文对象,可以获取属性值,获取类加载器,获取BeanFactory等。

                • metadata:元数据对象,用于获取注解属性。

② 判断条件: 在初始化Bean时,使用 @Conditional(条件类.class)注解

SpringBoot 提供的常用条件注解:

一下注解在springBoot-autoconfigure的condition包下

  • ConditionalOnProperty:判断配置文件中是否有对应属性和值才初始化Bean
  • ConditionalOnClass:判断环境中是否有对应字节码文件才初始化Bean
  • ConditionalOnMissingBean:判断环境中没有对应Bean才初始化Bean
  • ConditionalOnBean:判断环境中有对应Bean才初始化Bean

可以查看RedisAutoConfiguration类说明以上注解使用

二,@Enable

SpringBoot中提供了很多Enable开头的注解,这些注解都是用于动态启用某些功能的。而其底层原理 是使用@Import注 解导入一些配置类,实现Bean的动态加载

@Import注解

@Enable底层依赖于@Import注解导入一些类,使用@Import导入的类会被Spring加载到IOC容器中。 而@Import提供4中用法:

        ① 导入Bean

        ② 导入配置类

        ③ 导入 ImportSelector 实现类。一般用于加载配置文件中的类

        ④ 导入 ImportBeanDefinitionRegistrar 实现类。

导入demo4,以坐标形式
 <!--导入坐标-->
        <dependency>
            <groupId>com.apesource</groupId>
            <artifactId>springboot-enable_other-04</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
demo3导入
@SpringBootApplication
//@Import(User.class)
//@Import(UserConfig.class)
//@Import(MyImportSelector.class)
@Import({MyImportBeanDefinitionRegistrar.class})
//@EnableCaching
//@EnableAsync
public class SpringbootEnable03Application {

    public static void main(String[] args) {

        ConfigurableApplicationContext context =  SpringApplication.run(SpringbootEnable03Application.class, args);
        /**
         * Import4中用法:
         *  1. 导入Bean
         *  2. 导入配置类
         *  3. 导入ImportSelector的实现类
         *      查看ImportSelector接口源码
         *          String[] selectImports(AnnotationMetadata importingClassMetadata);
         *          代表将“字符串数组”中的的类,全部导入spring容器
         *  4. 导入ImportBeanDefinitionRegistrar实现类
         *
         */
//        User user = context.getBean(User.class);
//        System.out.println(user);
//
//        Student student = context.getBean(Student.class);
//        System.out.println(student);

        User user = (User) context.getBean("user");
        System.out.println(user);

    }

}
UserConfig类
@Configuration
public class UserConfig {

    @Bean
    public User user() {
        return new User();
    }
}
EnableUser注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(UserConfig.class)
public @interface EnableUser {
}
MyImportSelector 
public class MyImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        //目前字符串数组的内容是写死的,未来可以设置在配置文件中动态加载
        return new String[]{"com.apesource.domain.User", "com.apesource.domain.Student"};
    }
}
MyImportBeanDefinitionRegistrar 
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        //AnnotationMetadata注解
        //BeanDefinitionRegistry向spring容器中注入

        //1.获取user的definition对象
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(User.class).getBeanDefinition();

        //2.通过beanDefinition属性信息,向spring容器中注册id为user的对象
        registry.registerBeanDefinition("user", beanDefinition);

    }
}

三,spring boot自动装配

@EnableAutoConfiguration 注解
主启动类

//@SpringBootApplication 来标注一个主程序类
//说明这是一个Spring Boot应用
@SpringBootApplication
public class SpringbootApplication {
   public static void main(String[] args) {
     //以为是启动了一个方法,没想到启动了一个服务
      SpringApplication.run(SpringbootApplication.class, args);
   }
}
@SpringBootApplication注解内部
@SpringBootConfiguration
@EnableAutoConfiguration//自动配置
@ComponentScan(//扫描
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
    // ......
}
@ComponentScan

这个注解在Spring中很重要 ,它对应XML配置中的元素。 作用:自动扫描并加载符合条件的组件或者bean , 将这个bean定义加载到IOC容器中

@SpringBootConfiguration 作用:

SpringBoot的配置类 ,标注在某个类上 , 表示这是一个SpringBoot的配置类;

//@SpringBootConfiguration注解内部
//这里的 @Configuration,说明这是一个配置类 ,配置类就是对应Spring的xml 配置文件;
@Configuration
public @interface SpringBootConfiguration {}
//里面的 @Component 这就说明,启动类本身也是Spring中的一个组件而已,负责启动应用
@Component
public @interface Configuration {}
@AutoConfigurationPackage :自动配置包
//AutoConfigurationPackage的子注解
//Registrar.class 作用:将主启动类的所在包及包下面所有子包里面的所有组件扫描到Spring容器 
@Import({Registrar.class})
public @interface AutoConfigurationPackage {
}
@EnableAutoConfiguration开启自动配置功能

以前我们需要自己配置的东西,而现在SpringBoot可以自动帮我们配置 ;@EnableAutoConfiguration 告诉SpringBoot开启自动配置功能,这样自动配置才能生效;  

@Import({AutoConfigurationImportSelector.class}) :给容器导入组件 ; AutoConfigurationImportSelector :自动配置导入选择器,给容器中导入一些组件

AutoConfigurationImportSelector.class
 ↓
    selectImports方法
   ↓
this.getAutoConfigurationEntry(annotationMetadata)方法
 ↓
this.getCandidateConfigurations(annotationMetadata, attributes)方法
 ↓
方法体:
 List<String> configurations = 
SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass
(), this.getBeanClassLoader());
        Assert.notEmpty(configurations, "No auto configuration classes found in 
META-INF/spring.factories. If you are using a custom packaging, make sure that 
file is correct.");
        return configurations;
 ↓
在所有包名叫做autoConfiguration的包下面都有META-INF/spring.factories文件
总结原理:
  • @EnableAutoConfiguration 注解内部使用 @Import(AutoConfigurationImportSelector.class) 来加载配置类。
  • 配置文件位置:META-INF/spring.factories,该配置文件中定义了大量的配置类,当 SpringBoot 应用启动时,会自动加载这些配置类,初始化Bean
  • 并不是所有的Bean都会被初始化,在配置类中使用Condition来加载满足条件的Bean
自定义启动器

需求: 自定义redis-starter,要求当导入redis坐标时,SpringBoot自动创建Jedis的Bean

参考: 可以参考mybatis启动类的应用

实现步骤:
  • 创建redis-spring-boot-autoconfigure模块
  • 创建redis-spring-boot-starter模块,依赖redis-spring-boot-autoconfigure的模块
  • 在redis-spring-boot-autoconfigure模块中初始化Jedis的Bean,并定义METAINF/spring.factories文件
  • 在测试模块中引入自定义的redis-starter依赖,测试获取Jedis的Bean,操作redis。
实现:模拟自定义配置

redis-spring-boot-autoconfigure

<!--引入jedis依赖-->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
RedisAutoconfiguration
@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class RedisAutoconfiguration {
    //注入jedis
    @Bean
    public Jedis jedis(RedisProperties redisProperties){
        return new Jedis(redisProperties.getHost(),redisProperties.getPort());
    }
}

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.apesource.RedisAutoconfiguration
redis-spring-boot-starter
<dependency>
            <groupId>com.apesource</groupId>
            <artifactId>redis-spring-boot-autoconfigure</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
springboot-enable_other-04
<!--导入坐标-->
        <dependency>
            <groupId>com.apesource</groupId>
            <artifactId>redis-spring-boot-starter</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

启动

@SpringBootApplication
public class SpringbootEnable03Application {

    public static void main(String[] args) {

        ConfigurableApplicationContext context =  SpringApplication.run(SpringbootEnable03Application.class, args);
        Jedis bean1 = context.getBean(Jedis.class);
        System.out.println(bean1);
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2052282.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Adobe After Effects AE V2023-23.6.6.2 解锁版下载安装教程 (视频合成和特效制作)

前言 Adobe After Effects&#xff08;简称AE&#xff09;是一款专业的图形视频处理软件&#xff0c;数字影视特效合成软件&#xff0c;视频后期特效制作软件。主要用来创建动态图形和视觉特效&#xff0c;支持2D以及3D&#xff0c;是基于非线性编辑的软件&#xff0c;透过图层…

原生js用Export2Excel导出excel单级表头和多级表头数据方式实现

原生js用Export2Excel导出excel单级表头和多级表头数据方式实现 原生js用Export2Excel导出excel单级表头和多级表头数据方式实现HTML文件导入需要的文件HTML文件中实现导出函数HTML总代码实现汇总&#xff08;直接复制代码&#xff0c;注意js引入路径&#xff09; 原生js用Expo…

小区社区超市商城停车场管理系统-计算机毕设Java|springboot实战项目

&#x1f34a;作者&#xff1a;计算机毕设匠心工作室 &#x1f34a;简介&#xff1a;毕业后就一直专业从事计算机软件程序开发&#xff0c;至今也有8年工作经验。擅长Java、Python、微信小程序、安卓、大数据、PHP、.NET|C#、Golang等。 擅长&#xff1a;按照需求定制化开发项目…

Ai学术叫叫兽全网最新创新点改进系列:丰富文章的热力图如何制作,论文装逼必用神器!极大丰富文章内容,并提升论文实验效果及其质量!

Ai学术叫叫兽全网最新创新点改进系列&#xff1a;丰富文章的热力图如何制作&#xff0c;论文装逼必用神器&#xff01;极大丰富文章内容&#xff0c;并提升论文实验效果及其质量&#xff01; 所有改进代码均经过实验测试跑通&#xff01;截止发稿时YOLOv8、YOLOv10均已改进40&…

tekton什么情况下在Dockerfile中需要用copy

kaniko配置如下 如果docker中的workDir跟tekton中的workDir不一致需要copy。也可以通过mv&#xff0c;cp达到类似效果

大数据——Flink原理

摘要 Apache Flink是一个框架和分布式处理引擎&#xff0c;用于对无界和有界数据流进行有状态计算。Flink被设计在所有常见的集群环境中运行&#xff0c;以内存执行速度和任意规模来执行计算。 1. FLink特点 1.1. 事件驱动型(Event-driven) 事件驱动型应用是一类具有状态的应…

基于 NXP LPC5516 + MC33665 + MC33774 的菊花链 HVBMS 储能方案

在 ESS 储能系统中&#xff0c;HVBMS 一般会采用两级或三级架构&#xff0c;从而实现从电池模组到电池簇&#xff0c;再到电池堆的分级管理和控制。本方案则给大家讲解基于 LPC5516 MC33665 MC33774 菊花链 HVBMS 方案&#xff0c;涵盖了 BMU、BJB、CMU&#xff0c;构建 HVBM…

简洁清新个人博客网页模板演示学习

30多款个人博客、个人网站、个人主页divcss,html在线预览,个人静态页面模板(wordpress、帝国cms、typecho主题模板).这些简洁和优雅的博客网页模板,为那些想成为创建博客的个人或媒体提供灵感设计。网页模板可以记录旅游、生活方式、食品或摄影博客等网站。部分网页模板来源网友…

MySQL8.0.0.28数据库安装配置

MySQL8.0.0.28数据库安装配置 1. 安装前的准备工作 1.1 确认目前服务器上是否存在MySQL 命令&#xff1a;rpm -qa | grep mysql 说明&#xff1a;若返回空信息&#xff0c;就说明当前环境没有安装MySQL&#xff1b;直接跳到第4步操作后续。 1.2 检查当前环境是否有自带的m…

系统编程-文件属性和目录操作

4 文件属性和目录操作 一、目录操作 -- 目录操作主要的目的&#xff1a;让程序知道路径下有什么文件存在 -- 注&#xff1a;程序在哪里运行他的工作路径就在哪里 &#xff0c;程序中所有的相对路径的文件就是基于工作路径来实现的 1、获取当前程序运行的工作路径 -- 函数头…

爬取豆瓣TOP250电影详解

一.分析网页DOM树结构 1.分析网页结构及简单爬取 豆瓣&#xff08;Douban&#xff09;是一个社区网站&#xff0c;创立于2005年3月6日。该网站以书影音起家&#xff0c;提供关于书籍、电影、音乐等作品的信息&#xff0c;其作品描述和评论都是由用户提供&#xff08;User-Gen…

MATLAB 手动实现一种高度覆盖值提取建筑物点云的方法(74)

专栏往期文章,包含本章 MATLAB 手动实现一种高度覆盖值提取建筑物点云的方法(74) 一、算法介绍二、算法实现1.代码2.效果总结一、算法介绍 手动实现一种基于高度覆盖值的建筑物点云提取方法,适用于高大的城市建筑物,比只利用高度提取建筑物的方法更加稳定和具有价值,主要…

NC 丑数

系列文章目录 文章目录 系列文章目录前言 前言 前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到网站&#xff0c;这篇文章男女通用&#xff0c;看懂了就去分享给你的码吧。 描述 把只包含质因…

Linux_Shell三剑客grep,awk,sed-08

三剑客的概述&#xff1a; awk、grep、sed是linux操作文本的三大利器&#xff0c;合称文本三剑客&#xff0c;也是必须掌握的linux命令之一。三者的功能都是处理文本&#xff0c;但侧重点各不相同&#xff0c;其中属awk功能最强大&#xff0c;但也最复杂。grep更适合单纯的查找…

英伟达开源 Nemotron-4-4B:小型模型,大能量

前沿科技速递&#x1f680; 在人工智能领域&#xff0c;语言模型已经成为推动自然语言处理&#xff08;NLP&#xff09;进步的关键力量。然而&#xff0c;随着模型规模的不断扩大&#xff0c;训练和部署这些大型语言模型&#xff08;LLM&#xff09;的资源成本也在急剧增加。为…

2024年8月 trueNas 容器端口只能设置大于9000问题解决

前言 这两天在搭建个人nas&#xff0c;想顺便在局域网搭建一个dns服务器&#xff0c;我采用的是jpillora/dnsmasq的docker镜像搭建的&#xff0c;但是遇到一个问题始终无法解决容器端口必须大于9000&#xff0c;而dns使用的端口是53是改不了的&#xff0c;找了很多资料发现有老…

地图相册系统的设计与实现

摘 要 随着信息技术和网络技术的飞速发展&#xff0c;人类已进入全新信息化时代&#xff0c;传统管理技术已无法高效&#xff0c;便捷地管理信息。为了迎合时代需求&#xff0c;优化管理效率&#xff0c;各种各样的管理系统应运而生&#xff0c;各行各业相继进入信息管理时代&a…

Transformer 中自注意力机制的 一些细节理解

摘自知乎博主https://www.zhihu.com/question/362131975/answer/2182682685?utm_oi78365163782144 作者&#xff1a;月来客栈 链接&#xff1a;https://www.zhihu.com/question/362131975/answer/2182682685 1. 多头注意力机制原理 1.1 动机 首先让我们先一起来看看作者当…

IP SSL证书快速申请教程

在互联网安全领域中&#xff0c;SSL证书是比较普遍的传输数据加密方式之一。SSL证书通过建立加密通道&#xff0c;确保客户端与服务器之间传输的数据不被第三方窃取或篡改。而大多数SSL证书&#xff0c;如单域名SSL证书、多域名SSL证书以及通配符SSL证书&#xff0c;在申请时必…

颇为实用的现代化开源数据表格GristCore

GristCore&#xff1a;用Grist&#xff0c;让数据自动化&#xff0c;让工作更智能。 - 精选真开源&#xff0c;释放新价值。 概览 Grist-core项目是Grist的心脏&#xff0c;是一个创新的在线数据协作平台&#xff0c;它突破了传统电子表格的局限&#xff0c;引入了先进的自动化…