@Conditional注解是帮助我们更加方便的去创建bean,类似于@Profile.这里学习一个例子来来展示@Conditional注解如何帮助我们更加灵活的创建bean.
首先设定两个条件,当符合这两个条件时我们分别创建不同的bean
判定程序是否运行在weindows 环境
/**
* Created by lengshan on 2018/4/10 0010.
*/
public class WindowsCondition implements Condition {
//获取系统的环境变量
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
return conditionContext.getEnvironment().getProperty("os.name").contains("Windows");
}
}
判定程序是否运行在linux环境中
/**
* Created by lengshan on 2018/4/10 0010.
*/
public class LinuxCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
return conditionContext.getEnvironment().getProperty("os.name").contains("Linux");
}
}
创建一个接口,并且分别创建实现这个接口的两个实现类,后面我们根据前面的两个条件来判断容器调用哪个实现类去创建bean
创建接口
/**
* Created by lengshan on 2018/4/10 0010.
*/
public interface ListService {
public String showListService();
}
创建实现类
/**
* Created by Administrator on 2018/4/10 0010.
*/
public class LinuxListService implements ListService {
@Override
public String showListService() {
return "ls";
}
}
/**
* Created by Administrator on 2018/4/10 0010.
*/
public class WindowsListService implements ListService {
@Override
public String showListService() {
return "dir";
}
}
最重要的编写配置文件,这里具体应该@Conditional注解来帮助我们判断去创建哪个bean
/**
* Created by lengshan on 2018/4/10 0010.
*/
@Configuration
//@ComponentScan("com.example.demo")
public class MyConfig {
@Bean
@Conditional(WindowsCondition.class)
public ListService windowsListService(){
return new WindowsListService();
}
@Bean
@Conditional(LinuxCondition.class)
public ListService linusListService(){
return new LinuxListService();
}
}
编写main,并输出返回值。当程序运行在linux下时返回ls,运行在windows下时返回dir
@SpringBootApplication
public class DemoSpringcongditionalApplication {
public static void main(String[] args) {
SpringApplication.run(DemoSpringcongditionalApplication.class, args);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
ListService listService = context.getBean(ListService.class);
System.out.println(listService.showListService());
context.close();
}
}
参考:《Java EE开发的颠覆者 spring boot实战》