案例2:
在Spring的IOC容器中有一个User的Bean,现要求:某个字节码存在就创建该Bean。不存在不创建。
1、引入依赖
<dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId>
</dependency>
2、自定义注解:@ConditionOnclass
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(ClassCondition.class)
public @interface ConditionOnclass {String[] value();
}
3、加入@ConditionOnclass注解
@Configurable
public class UserConfig {@Bean//@Conditional(ClassCondition.class)@ConditionOnclass("redis.clients.jedis.Jedis")public User user(){return new User();}
}
4、编写ClassCondition
public class ClassCondition implements Condition {@Overridepublic boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {//导入通过注解属性值value指定坐标后创建Bean//获取注解属性值 valueMap<String, Object> map = metadata.getAnnotationAttributes(ConditionOnclass.class.getName());String[] value=(String[]) map.get("value");boolean flag=true;try {for (String className : value) {Class<?> aClass = Class.forName(className);}} catch (ClassNotFoundException e) {flag=false;}return flag;}
}
运行结果
注释掉jedis依赖
SpringBoot提供的常用条件注解:
ConditionalOnProperty:判断配置文件中是否有对应属性和值才初始化Bean
ConditionalOnClass:判断环境中是否有对应字节码文件才初始化Bean
ConditionalOnMissingBean:判断环境中有没有对应Bean才初始化Bean