1: The need to inject a bean
/ ** * selective implantation bean. . The window, linux system injects a different value * / @Configuration public class Cap5Config { / * Linux system injects attribute * / @Bean ( "linuxuser" ) @Conditional (LinuxCondition. Class ) public the User linuxuser () { return new new the User ( "linuxuser", 26 is ); } / * the Window injection system attribute * / @Bean ( "windowUser" ) @Conditional (value . WindowCondition = class ) // selective implantation (@Bean annotation requires complex) public User windowUser() { return new User("windowUser", 26); }
2: Setting the registration conditions
/ ** * Registered targeted bean: Analyzing conditions used in the context * / public class WindowCondition the implements for condition Condition { @Override public Boolean The matches (ConditionContext context, AnnotatedTypeMetadata Metadata) { Environment Environment = Context.getEnvironment (); String window = Environment. getProperty ( "The os.name" ); IF (window.contains ( "Win")) return to true ; return to false ; } }
3: labeling conditions
@Conditional(value = WindowCondition.class)
4: Test
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); } } }