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

发布于:2024-05-04 ⋅ 阅读:(57) ⋅ 点赞:(0)

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

从一个案例出发学习Condition

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

没加condition的情况

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

@Component
public class User {
}

2、创建配置类

@Configurable
public class UserConfig {

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

3、获取user,打印出来

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注解,查看这个注解。

@Configurable
public class UserConfig {
   @Bean
   @Conditional()
    public User user(){
        return new User();
    }
}

查看 @Conditional

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

查看Condition接口 

@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依赖

 <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

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

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注解

@Configurable
public class UserConfig {
   @Bean
   @Conditional(ClassCondition.class)
    public User user(){
        return new User();
    }
}

运行结果:

注释掉jedis依赖,结果

 


网站公告

今日签到

点亮在社区的每一天
去签到