
正文
Springboot 条件注解
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
-
@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
-







