@Conditional:Spring4.0 介绍了一个新的注解@Conditional,它的逻辑语义可以作为"If…then…else…"来对bean的注册起作用。
- 作用:根据条件,决定类是否加载到Spring Ioc容器中,在SpringBoot中有大量的运用;
- 应用场景:在一些需要条件满足才是实例化的类中,使用此注解,根据配置文件的不同,来决定这个bean是否加载至ioc容器中。
- 依赖:org.springframework.context.annotation
一.Condition接口介绍
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.context.annotation;
import org.springframework.core.type.AnnotatedTypeMetadata;
@FunctionalInterface
public interface Condition {
// ConditionContext context: spring容器上下文环境,可获取配置文件信息
boolean matches(ConditionContext var1, AnnotatedTypeMetadata var2);
}
二.使用方法
- 自定义一个类,实现Conditional接口, 实现matches方法;
public class LinuxCondition implements Condition {
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
// 从配置文件获取系统环境的属性
String systemName = context.getEnvironment().getProperty("os.name");
if(systemName.contains("Linux")){
return true;
}
return false;
}
}
- 在需要判断条件的bean上,加 @Conditional(LinuxCondition.class) ,即可在满足条件,返回值为 true 的时候加载对应的类;
@Bean
@Conditional(LinuxCondition.class)
public TestBean getTestBean(){
TestBean testBean = new TestBean();
return testBean;
}
- 作用在类上;
// 可以配合Spring的容器使用
@RestController
@Conditional({LinuxCondition.class})
public class AcsController {
// 如果配合@RestController、@Component等注解使用,当满足条件时,Spring会创建bean;
}
// 可以配合@Configuration注解使用
@Configuration
@Conditional({LinuxCondition.class})
public class AppConfig {
@Bean
public TransferService transferService() {
return new TransferServiceImpl();
}
}
- 多个条件作用在类上,满足全部条件才会初始化bean;
// 定义条件-01
public class WindowsCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String systemName = context.getEnvironment().getProperty("os.name");
if(systemName.contains("Windows")){
return true;
}
return false;
}
}
// 定义条件-02
public class OsxCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String property = context.getEnvironment().getProperty("os.name");
if(property.equals("Mac OS X")){
return true;
}
return false;
}
}
@RestController
@Conditional(value = {OsxCondition.class,TestCondition.class})
public class AcsController {
// 条件全部满足才会初始化
}