标签:welcome etl nfa override strong spring -- win7 实例化
下面来介绍如何使用@Condition
@Conditional(TestCondition.class)
这句代码可以标注在类上面,表示该类下面的所有@Bean都会启用配置,也可以标注在方法上面,只是对该方法启用配置。
spring框架还提供了很多@Condition给我们用,当然总结用语哪种好理解,看给位读者喽
@ConditionalOnBean(仅仅在当前上下文中存在某个对象时,才会实例化一个Bean)
@ConditionalOnClass(某个class位于类路径上,才会实例化一个Bean)
@ConditionalOnExpression(当表达式为true的时候,才会实例化一个Bean)
@ConditionalOnMissingBean(仅仅在当前上下文中不存在某个对象时,才会实例化一个Bean)
@ConditionalOnMissingClass(某个class类路径上不存在的时候,才会实例化一个Bean)
@ConditionalOnNotWebApplication(不是web应用)
后续会继续补充
另一种总结
public class InitConditional implements Condition{ @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { //判断是否已经包含了amazonTest Bean Boolean bol = conditionContext.getBeanFactory().containsBean("amazonTest"); return bol; } }
使用自定义的Conditional
@Component @Conditional(InitConditional.class) public class AmazonTest { @Autowired private AmazonProperties amazonProperties; public void testGet(){ System.out.println(" testGet Associated"); System.out.println(amazonProperties.getAssociateId()); } }
WelcomeController 与 AmazonTest关联,使用ConditionOnBean(如果条件的bean存在,当前的bean才会被声明)
@Component @ConditionalOnBean(AmazonTest.class) public class WelcomeController { private static final Logger logger = LoggerFactory.getLogger(WelcomeController.class); private AppProperties app; private GlobalProperties global; @Autowired public void setApp(AppProperties app) { this.app = app; } @Autowired public void setGlobal(GlobalProperties global) { this.global = global; } public void testWelcome(){ String appProperties = app.toString(); String globalProperties = global.toString(); System.out.println(appProperties); System.out.println(globalProperties); } }
main测试文件入口
public static void main(String[] args) { ConfigurableApplicationContext configurableApplicationContext =SpringApplication.run(DemoApplication.class, args); //bean自动注册,根据bean的名字获取Bean AmazonProperties amazonProperties = (AmazonProperties) configurableApplicationContext.getBean("amazonProperties"); System.out.println(amazonProperties.getAssociateId()); Boolean aBooleanWelcomeController = configurableApplicationContext.containsBean("welcomeController"); if(!aBooleanWelcomeController){ System.out.println(" welcomeController init fail"); }else{ WelcomeController welcomeController = (WelcomeController) configurableApplicationContext.getBean("welcomeController"); System.out.println(" welcomeController init Success"); } Boolean aBooleanAmazonTest = configurableApplicationContext.containsBeanDefinition("amazonTest"); if(!aBooleanAmazonTest){ System.out.println(" amazonTest init fail"); }else{ AmazonTest amazonTest = (AmazonTest) configurableApplicationContext.getBean("amazonTest"); System.out.println(" amazonTest init Success"); } }
springBoot----@ConditionalOnxxx相关注解总结
标签:welcome etl nfa override strong spring -- win7 实例化
原文地址:https://www.cnblogs.com/jiligalaer/p/12070623.html