1. @Conditional注解根据满足的条件来创建一个特定的Bean
2. 示例,以不同的操作系统为条件,通过实现Condition接口,并重写matches方法来构造判断条件,若在Windows系统下运行程序,则输出命令dir, 若在Linux系统下运行则输出 ls
3. 编写判断Windows的条件类
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.stereotype.Service;
@Service
public class WindowsCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getEnvironment().getProperty("os.name").contains("Windows");
}
}
4. 编写判断Linux的条件类
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.stereotype.Service;
@Service
public class LinuxCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getEnvironment().getProperty("os.name").contains("Linux");
}
}
5. 不同系统下Bean的共同接口
public interface ListCmdService {
public String showCmd();
}
6. Windows系统下创建的Bean类
public class ListWindowsCmd implements ListCmdService {
@Override
public String showCmd() {
return "dir";
}
}
7. Linux系统下创建的Bean类
public class ListLinuxCmd implements ListCmdService {
@Override
public String showCmd() {
return "ls";
}
}
8. 配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ConditionConfig {
@Bean
@Conditional(WindowsCondition.class)
public ListCmdService listWindowsCmd() {
return new ListWindowsCmd();
}
@Bean
@Conditional(LinuxCondition.class)
public ListCmdService listLinuxCmd() {
return new ListLinuxCmd();
}
}
代码解释:@Conditional注解,符合WindowsCondition条件则创建ListWindowsCmd实例,符合LinuxCondition条件则创建ListLinuxCmd实例
9. 运行
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(ConditionConfig.class);
ListCmdService listCmdService = context.getBean(ListCmdService.class);
System.out.println(context.getEnvironment().getProperty("os.name") +
" 系统命令:" + listCmdService.showCmd());
}
}