今天给大家说一下springboot中@Conditional注解的作用,在我们常用的声明一个配置类时,我们都会采用注解的方法,@Configuration和@Bean一起搭配使用,@Configuration是指明当前类是一个配置类,就是代替之前的spring配置文件,在配置文件中用标签添加组件,但是现在有注解
- @Bean:就是将方法的返回值添加到容器中,容器中的这个组件默认的id就是方法名
当我们再了解springboot自动装配的源码中,我们会发现有很多的组件,springboot在启动时会去加载,会发现在META-INF下会有spring.factories的配置,而且在配置时会从properties类中获取属性,我们可以在配置文件中指定这些属性的值。但是在用@Configuration注解时,我们可以指定满足什么条件才会向容器中添加组件。就是我们下面要扩展的。Condition是一个接口,接口中有一个matches方法,返回值类型是boolean类型.今天我们只说@Conditional的使用,其他的都是一样的。
下面用代码举例子说明一下,首先定义一个实体类
@Data
@AllArgsConstructor
public class Person {
private String name;
private int age;
}
我们可以自定义一个类实现Condition接口。
public class ConditionalDemo1 implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
Environment environment = conditionContext.getEnvironment();
String property = environment.getProperty("os.name");
if(property.contains("Windows")){
return true;
}
return false;
}
}
接下来写一个配置类
@Configuration
public class PersonConfigure {
@Bean(name="bill")
@Conditional({ConditionalDemo1.class})//如果满足ConditionalDemo1返回true,继续加载下面这个方法
public Person person1(){
return new Person("Bill Gates",62);
}
}
简单测试一下,
@RestController
public class ConditionalController {
@Autowired
ApplicationContext applicationContext;
@RequestMapping("/cconditionalTest")
public Person showe(){
boolean flag=applicationContext.containsBean("bill");
Person bill =(Person) applicationContext.getBean("bill");
return bill;
}
}
结果我们发现返回了Person的信息,说明 @Conditional({ConditionalDemo1.class})满足了,才会实现把Person注入到spring容器中。大家可以试一下,很简单的。