1:需要注入的bean
/** * 选择性注入bean。。根据window,linux系统注入不同的值 */ @Configuration public class Cap5Config { /* linux系统注入的属性 */ @Bean("linuxUser") @Conditional(LinuxCondition.class) public User linuxUser() { return new User("linuxUser", 26); } /* Window系统注入的属性 */ @Bean("windowUser") @Conditional(value = WindowCondition.class) //选择性注入(需要配合@Bean注解) public User windowUser() { return new User("windowUser", 26); }
2:设置注册条件
/** * 针对性注册bean:判断条件使用的上下文环境 */ public class WindowCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { Environment environment = context.getEnvironment(); String window = environment.getProperty("os.name"); if (window.contains("Win")) return true; return false; } }
3:标记条件
@Conditional(value = WindowCondition.class)
4:测试
public class ConditionApplication { public static void main(String[] args) { AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(Cap5Config.class); String[] beanDefinitionNames = annotationConfigApplicationContext.getBeanDefinitionNames(); for (String beanName : beanDefinitionNames) { //获取注入的所有的bean并打印 System.out.println(beanName); } } }