SpringBoot之@Conditional注解实现选择性的创建Bean操作

Condition 是在Spring 4.0增加的条件判断功能,通过这个功能可以实现选择性的创建Bean操作。即满足这个条件才帮我们创建Bean。

从一个案例出发学习Condition

需求:在Spring的IOC容器中有一个User的Bean,现要求:导入Jedis坐标后,加载该Bean,没导入,则不加载。

没加condition的情况

1、先创建一个名为User的Bean

java 复制代码
@Component
public class User {
}

2、创建配置类

java 复制代码
@Configurable
public class UserConfig {

   @Bean
    public User user(){
        return new User();
    }
}

3、获取user,打印出来

java 复制代码
public static void main(String[] args) {
    ConfigurableApplicationContext context = SpringApplication.run(SpringbootConditionApplication.class, args);
    Object user = context.getBean("user");
    System.out.println(user);

}

此时运行结果:可以得到user

@Conditional注解

我们在代码中加入一个@Conditional注解,查看这个注解。

java 复制代码
@Configurable
public class UserConfig {
   @Bean
   @Conditional()
    public User user(){
        return new User();
    }
}

查看 @Conditional

java 复制代码
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {
    Class<? extends Condition>[] value();
}

查看Condition接口

java 复制代码
@FunctionalInterface
public interface Condition {
    boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);
}

使用时,加入@Conditional注解,里面传一个public interface Condition接口的实现类,并且复写matches方法,返回true或者false。如果返回true。那么这个bean将被spring容器创建。

参数context:上下文对象,用于获取环境、IOC容器、ClassLoader对象

参数metadata注解元对象,用于获取注解定义的属性值

使用注解:实现导入Jedis坐标后,加载该Bean,没导入,则不加载。

1、导入jedis依赖

java 复制代码
 <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

2、创建ClassCondition类实现Condition接口,重写matches方法。

java 复制代码
public class ClassCondition implements Condition {
    @Override
    //判断import redis.clients.jedis.Jedis文件是否存在,
   //存在,就表示导入了jedis

    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        boolean flag=true;
        try {
            Class<?> aClass = Class.forName("redis.clients.jedis.Jedis");
        } catch (ClassNotFoundException e) {
            flag=false;
        }
        return flag;
    }
}

3、加入@Conditional注解

java 复制代码
@Configurable
public class UserConfig {
   @Bean
   @Conditional(ClassCondition.class)
    public User user(){
        return new User();
    }
}

运行结果:

注释掉jedis依赖,结果

相关推荐
zym大哥大2 分钟前
Redis-Zest
数据库·redis·缓存
源码7可24 分钟前
Java高手速成--吃透源码+手写组件+定制开发
java
zl97989924 分钟前
Redis-stream、bitfield类型
数据库·redis·缓存
zjjuejin27 分钟前
Maven 云原生时代面临的八大挑战
java·后端·maven
ZhengEnCi28 分钟前
@RequestParam 注解完全指南-从参数绑定到接口调用的Web开发利器
java·spring boot
=>>漫反射=>>39 分钟前
单元测试 vs Main方法调试:何时使用哪种方式?
java·spring boot·单元测试
初圣魔门首席弟子39 分钟前
c++ bug 记录(merge函数调用时错误地传入了vector对象而非迭代器。)
java·c++·bug
cxyxiaokui00142 分钟前
🔍 为什么我的日志在事务回滚后也没了?——揭秘 REQUIRES_NEW 的陷阱
java·后端·spring
ZhengEnCi1 小时前
@Parameter 注解技术解析-从 API 文档生成到接口描述清晰的 SpringBoot 利器
java·spring boot
数据库那些事儿1 小时前
Qoder + ADB Supabase :5分钟GET超火AI手办生图APP
数据库·后端