原理:
是通过Condition接口判断pom.xml有没有导入某个坐标或者依赖某个坐标而进行加载某个bean。
Condition是Spring4.0后引入的条件化配置接口,通过实现Condition接口能够实现有条件的加载相应的Bean,
而后通过@Conditional注解,要配和Condition的实现类(ClassCondition)进行应用
需要
在spring的ioc容器中有一个User的Bean,如果pom.xml导入了Jedis坐标后,就加载该Bean,否则不加载
代码实现:
1、先创立一个user对象
public class User {
}
2、创立一个UserConfig.java的配置类,生成User对象的Bean
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class UserConfig {
@Bean
public User user(){
return new User();
}
}
3、在Springboot的启动类中获取User对象的Bean
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(DemoApplication.class, args);
//在Springboot的启动类中获取User对象的Bean
Object user = run.getBean("user");
System.out.println(user);//输出:com.example.demo.User@6724cdec
}
}
以上是不论什么时候都能加载User对象的Bean,然而咱们的需要是如果pom.xml导入了Jedis坐标后,就加载该Bean,否则不加载,所以接下来就行批改
代码革新
1、创立一个类实现Condition接口,重写matches办法,而后在办法外面写条件。返回true代表加载user对象的bean,返回false示意不加载
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class ClassCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
//需要:如果pom.xml导入了Jedis坐标后,就加载该User对象的Bean,否则不加载
boolean flag=true;
try {
//如果导入了Jedis坐标能够通过喷射的模式获取到Jedis对象。
Class<?> clazz = Class.forName("redis.clients.jedis.Jedis");
} catch (ClassNotFoundException e) {
//如果程序报错,证实没有导入Jedis坐标,所以获取不到
flag=false;
}
return flag;
}
}
2、在UserConfig.java类中创立User对象Bean 的办法上加上@Conditional(ClassCondition.class)注解,注解外面传入要判断的条件实现类,依据该类的matches办法的返回值进行操作,返回true代表能够加载User对象的bean,返回false示意不能够加载
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
@Configuration
public class UserConfig {
@Bean
@Conditional(ClassCondition.class) //退出条件判断的实现类,依据返回值判断是否要加载该bean
public User user(){
return new User();
}
}
4、测试
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
你在pom.xml导入了下面的坐标,运行springboot的启动类,如果有就失常获取,如果没有程序就会报错,提醒找不到user的bean
如果你在运行这个代码的过程中有遇到问题,请加小编vi信xxf960513,!帮忙你疾速把握这个性能代码!
发表回复