@Conditional的使用
- 作用:根據條件,決定類是否加載到Spring Ioc容器中,在SpringBoot中有大量的運用
- 應用場景:在一些需要條件滿足才是實例化的類中,使用此注解,我曾經在項目中需要根據不同的場景使用不同的mq中間件的時候使用過,在mq的實例化bean上,加上此注解,根據配置文件的不同,來決定這個bean是否加載至ioc容器中。
使用方法
-
實現Conditional接口, 實現matches方法。
public class MqExistsCondition implements Condition{ @Override public boolean matches(ConditionContext context,AnnotatedTypeMetadata metadata) { Environment environment = context.getEnvironment(); //從這里獲取配置文件中 active 的值,根據當前的active值決定是否加載類 String[] activeProfiles = environment.getActiveProfiles(); for (String active : activeProfiles) { if(active.equals(ActiveEnum.open_active.getActive().toString())){ return true; } } return false; } }
-
在需要判斷條件的bean上,加上**@Conditional(TestExistsCondition.class) **即可在滿足條件的時候加載對應的類。
@Bean @Conditional(TestMqExistsCondition.class) public TestBean getTestBean(){ TestBean testBean = new TestBean(); return testBean; }
其他派生的的conditional
@ConditionalOnClass
如果此class不存在
@ConditionalOnMissingBean
只有對應的ban在系統中都沒有被創建,它修飾的初始化代碼塊才會執行,用戶自己手動創建的bean優先
@ConditionalOnBean
僅僅在當前上下文中存在某個對象時,才會實例化一個Bean。
@ConditionalOnClass
某個class位於類路徑上,才會實例化一個Bean
@ConditionalOnExpression
當表達式為true的時候,才會實例化一個Bean。
比如:
@ConditionalOnExpression("true")
@ConditionalOnExpression("${my.controller.enabled:false}")
@ConditionalOnMissingBean
僅僅在當前上下文中不存在某個對象時,才會實例化一個Bean
@ConditionalOnMissingClass
某個class類路徑上不存在的時候,才會實例化一個Bean
@ConditionalOnNotWebApplication
不是web應用