“Yeah It’s on. ”
开头测试
快速创建springBoot项目,获取bean,redisTemplate

报错是必然的,因为根本就没导入redis坐标

导入坐标后再运行

实验案例
在Spring的IOC容器中有一个User的bean,现要求:
1、导入·jedis坐标后,加载该Bean,没导入,则不加载。

先加载Bean
2、实现判断
1
2
3
4
5
6
7
//classCondition
public class classCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return false;
}
}
1
2
3
4
5
6
7
8
9
10
11
/*userConfig*/
@Configuration
public class UserConfig {
@Bean
@Conditional(classCondition.class)
public User user(){
return new User();
}
}
因为classCondition中返回的是false,所以再运行时,user不会再被创建
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*classCondition*/
public class classCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
//导入jedis坐标后创建User
//怎么才能知道,导入了jedis
//思路 判断redis.clients.jedis.Jedis文件是否存在
boolean flag = true;
try {
Class<?> cls = Class.forName("redis.clients.jedis.Jedis");
} catch (ClassNotFoundException e) {
flag = false;
}
return flag;
}
}
如此,便能实现
代码在_doc中的condition中