• SpringBoot 自动配置


    Condition

    自定义条件:

    • 定义条件类:自定义类实现Condition接口,重写 matches 方法,在 matches 方法中进行逻辑判断,返回boolean值 。 matches 方法两个参数:
      • context:上下文对象,可以获取属性值,获取类加载器,获取BeanFactory等。
      • metadata:元数据对象,用于获取注解属性。
    • 判断条件: 在初始化Bean时,使用 @Conditional(条件类.class)注解

    SpringBoot 提供的常用条件注解:

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

    示例1:导入Jedis坐标后,加载该Bean,没导入,则不加载

    public class User {
    }
    
    • 1
    • 2
    public class Role {
    }
    
    • 1
    • 2
    @Configuration
    public class UserConfig {
    
        @Bean
        @Conditional(ClassCondition.class)
        public User user(){
            return new User();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    public class ClassCondition implements Condition {
        /**
         *
         * @param context 上下文对象。用于获取环境,IOC容器,ClassLoader对象
         * @param metadata 注解元对象。 可以用于获取注解定义的属性值
         * @return
         */
        @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;
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    @SpringBootApplication
    public class SpringbootConditionApplication {
    
        public static void main(String[] args) {
            //启动SpringBoot的应用,返回Spring的IOC容器
            ConfigurableApplicationContext context = SpringApplication.run(SpringbootConditionApplication.class, args);
            
            Object user = context.getBean("user");
            System.out.println(user);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

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

    @Configuration
    public class UserConfig {
    
        @Bean
        @ConditionOnClass("redis.clients.jedis.Jedis")
        public User user(){
            return new User();
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    @Target({ElementType.TYPE, ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Conditional(ClassCondition.class)
    public @interface ConditionOnClass {
        String[] value();
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    public class ClassCondition implements Condition {
        /**
         *
         * @param context 上下文对象。用于获取环境,IOC容器,ClassLoader对象
         * @param metadata 注解元对象。 可以用于获取注解定义的属性值
         * @return
         */
        @Override
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
            //获取注解属性值  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;
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    示例3:ConditionalOnProperty配置作用

    @Configuration
    public class UserConfig {
    
        @Bean
        @ConditionalOnProperty(name = "spring",havingValue = "zhangsan")
        public User user(){
            return new User();
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    application.properties

    spring=zhagnsan
    
    • 1

    @Import注解

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

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

    示例0:Enable

    @EnableUser
    @SpringBootApplication
    public class SpringbootEnableApplication {
    
        public static void main(String[] args) {
            ConfigurableApplicationContext context = SpringApplication.run(SpringbootEnableApplication.class, args);
    
            //获取Bean
            Object user = context.getBean("user");
            System.out.println(user);
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Import(UserConfig.class)
    public @interface EnableUser {
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    public class UserConfig {
    
        @Bean
        public User user() {
            return new User();
        }
    
        @Bean
        public Role role() {
            return new Role();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    示例一:导入Bean

    @Import(User.class)
    @SpringBootApplication
    public class SpringbootEnableApplication {
    
        public static void main(String[] args) {
            ConfigurableApplicationContext context = SpringApplication.run(SpringbootEnableApplication.class, args);
    
            User user = context.getBean(User.class);
            System.out.println(user);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    示例二:导入配置类

    public class UserConfig {
    
        @Bean
        public User user() {
            return new User();
        }
    
        @Bean
        public Role role() {
            return new Role();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    @Import(UserConfig.class)
    @SpringBootApplication
    public class SpringbootEnableApplication {
    
        public static void main(String[] args) {
            ConfigurableApplicationContext context = SpringApplication.run(SpringbootEnableApplication.class, args);
            
            User user = context.getBean(User.class);
            System.out.println(user);
    
            Role role = context.getBean(Role.class);
            System.out.println(role);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    示例3:导入ImportSelector的实现类

    public class MyImportSelector implements ImportSelector {
        @Override
        public String[] selectImports(AnnotationMetadata importingClassMetadata) {
            return new String[]{"com.release.domain.User", "com.release.domain.Role"};
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    @Import(MyImportSelector.class)
    @SpringBootApplication
    public class SpringbootEnableApplication {
    
        public static void main(String[] args) {
            ConfigurableApplicationContext context = SpringApplication.run(SpringbootEnableApplication.class, args);
    
            User user = context.getBean(User.class);
            System.out.println(user);
    
            Role role = context.getBean(Role.class);
            System.out.println(role);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    示例4:导入 ImportBeanDefinitionRegistrar 实现类

    public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
        @Override
        public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
            AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(User.class).getBeanDefinition();
            registry.registerBeanDefinition("user", beanDefinition);
            
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    @Import({MyImportBeanDefinitionRegistrar.class})
    @SpringBootApplication
    public class SpringbootEnableApplication {
    
        public static void main(String[] args) {
            ConfigurableApplicationContext context = SpringApplication.run(SpringbootEnableApplication.class, args);
    
            Object user = context.getBean("user");
            System.out.println(user);
            Map<String, User> map = context.getBeansOfType(User.class);
            System.out.println(map);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    @EnableAutoConfiguration 注解

    • @EnableAutoConfiguration 注解内部使用 @Import(AutoConfigurationImportSelector.class)来加载配置类。

    • 配置文件位置:META-INF/spring.factories,该配置文件中定义了大量的配置类,当 SpringBoot 应用启动时,会自动加载这些配置类,初始化Bean

    • 并不是所有的Bean都会被初始化,在配置类中使用Condition来加载满足条件的Bean

    示例:自定义redis-starter。要求当导入redis坐标时,SpringBoot自动创建Jedis的Bean。
    实现步骤:

    • 1.创建 redis-spring-boot-autoconfigure 模块
    • 2.创建 redis-spring-boot-starter 模块,依赖 redis-spring-boot-autoconfigure的模块
    • 3.在 redis-spring-boot-autoconfigure 模块中初始化 Jedis 的 Bean。并定义META-INF/spring.factories 文件
    • 4.在测试模块中引入自定义的 redis-starter 依赖,测试获取 Jedis 的Bean,操作 redis。

    3.在 redis-spring-boot-autoconfigure 模块中初始化 Jedis 的 Bean。并定义META-INF/spring.factories 文件

    @Configuration
    @EnableConfigurationProperties(RedisProperties.class)
    @ConditionalOnClass(Jedis.class)
    public class RedisAutoConfiguration {
    
    
        /**
         * 提供Jedis的bean
         */
        @Bean
        @ConditionalOnMissingBean(name = "jedis")
        public Jedis jedis(RedisProperties redisProperties) {
            System.out.println("RedisAutoConfiguration....");
            return new Jedis(redisProperties.getHost(), redisProperties.getPort());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    @ConfigurationProperties(prefix = "redis")
    public class RedisProperties {
    
        private String host = "localhost";
        private int port = 6379;
    
    
        public String getHost() {
            return host;
        }
    
        public void setHost(String host) {
            this.host = host;
        }
    
        public int getPort() {
            return port;
        }
    
        public void setPort(int port) {
            this.port = port;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    META-INF/spring.factories

    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
      com.release.redis.config.RedisAutoConfiguration
    
    • 1
    • 2

    4.在测试模块中引入自定义的 redis-starter 依赖,测试获取 Jedis 的Bean,操作 redis。

    @SpringBootApplication
    public class SpringbootEnableApplication {
    
        public static void main(String[] args) {
            ConfigurableApplicationContext context = SpringApplication.run(SpringbootEnableApplication.class, args);
    
            Jedis jedis = context.getBean(Jedis.class);
            System.out.println(jedis);
    
    		@Bean
        	public Jedis jedis(){
            	return  new  Jedis("123.56.72.62",6379);
        	}
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
  • 相关阅读:
    3. Python 变量和赋值
    什么是React中的高阶组件(Higher Order Component,HOC)?它的作用是什么?
    【每日一题】ABC202D - aab aba baa | 组合数 | 简单
    基于ssm+vue的班级同学录网站管理系统 elementui
    Linux 进程控制
    Vue中的.sync修饰符
    企业即时通讯怎样为企业实现移动办公效率的极致化?
    娄底高校实验室建设材料考虑
    PyTorch主要组成模块 | 数据读入 | 模型构建 | 模型初始化 | 损失函数 | 优化器 | 训练与评估
    google abseil c++ tips[55] name counting and unique_ptr 变量名计数和unique_ptr
  • 原文地址:https://blog.csdn.net/AliEnCheng/article/details/134331154