-
@Conditional
根据满足某一个特定条件创建一个特定的 Bean。就是根据特定条件来控制 Bean 的创建行为,这样我们可以利用这个特性进行一些自动的配置 - Springboot 中大量用到了条件注解
- 示例,以不同的操作系统作为条件,我们将通过实现
Condition
接口,并重写其matches()
方法来构造判断条件。若在 Windows 系统下运行程序,则输出列表命令为 dir ,若在 Linux 系统下运行程序,则输出列表命令为 ls-
判断 Window 条件
public class WindowsCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getEnvironment().getProperty("os.name").contains("Windows");
}
} -
判断 Linux 条件
public class LinuxCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getEnvironment().getProperty("os.name").contains("Linux ");
}
} -
不同系统下的 Bean 类
-
接口
public interface ListService {
String showListCmd();
} -
Window 下所要创建的 Bean 类
public class WindowsListService implements ListService{
@Override
public String showListCmd() {
return "dir";
}
} -
Linux 下所要创建的 Bean 类
public class LinuxListService implements ListService {
@Override
public String showListCmd() {
return "ls";
}
}
-
-
配置类
@Configuration
public class ConditionConfig { @Bean
@Conditional(WindowsCondition.class)
public ListService windowsListService(){
return new WindowsListService();
} @Bean
@Conditional(LinuxCondition.class)
public ListService linuxListService(){
return new LinuxListService();
} } -
测试类
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Ch522Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TaskTest { @Autowired
private ListService listService; @Test
public void conditionalTest() {
System.out.println(listService.showListCmd());
}
} -
测试结果
dir
-
相关文章
- springBoot+springSecurity 数据库动态管理用户、角色、权限
- 多条件查询--@Select注解里的动态sql语句
- 使用注解实现动态配置查询条件(一)
- 单链表为空的判定条件
- 记录一下SpringMVC扫描注解包的配置
- SpringBoot系列五:SpringBoot错误处理(数据验证、处理错误页、全局异常)
- 基于SpringBoot+Vue的企业安全评估系统设计与实现(源码+lw+远程部署)
- Spring定时任务@scheduled多线程的使用(@Async注解)
- iBatis动态条件查询 where的if条件不执行
- jenkins+windows+springboot+.net项目自动化部署图文教程