SpringBoot中使用Condition接口和Conditional注解装配Bean
一、使用Conditional注解,自己定义Condition接口
1、实现接口
public class GBKCondition implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { return true; } }
public class UTF8Condition ...
2、添加注解
@SpringBootConfiguration public class EncodingConvertConfig { @Bean @Conditional(UTF8Condition.class) public EncodingConvert createUTF8EncodingConvert(){ return new UTF8EncodingConvert(); } @Bean @Conditional(GBKCondition.class) public EncodingConvert createGBKEncodingConvert(){ return new GBKEncodingConvert(); } }
备注:matches方法返回true才会装配Bean
3、测试
@SpringBootApplication public class App { public static void main(String[] args) { ConfigurableApplicationContext context=SpringApplication.run(App.class,args); System.out.println(context.getBeansOfType(EncodingConvert.class)); context.close(); } }
备注:@Conditional({UTF8Condition.class,GBKCondition.class})表示同时返回true才会装配Bean
二、使用默认实现的一些Conditional注解
1、@ConditionalOnProperty:配置文件中存在且runnable.enble返回true时装配Bean
runnable.enble=true
@SpringBootConfiguration public class UserConfig { @Bean @ConditionalOnProperty(name="runnable.enble",havingValue="true") public Runnable createRunnable (){ return () -> {}; } }
备注:@ConditionalOnProperty(name="runnable.enble",havingValue="true",matchIfMissing = true),属性不存在或存在返回true都装配Bean
2、@ConditionalOnClass:classpath路径中存在指定的类则创建bean
如下:pom.xml中有gson依赖时可以装配Bean,去掉该依赖不会装配Bean
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency>
@Bean @ConditionalOnClass(name="com.google.gson.Gson") public Runnable createRunnable(){ return () -> {}; }
3、@ConditionalOnBean:如果某个bean存在时,则装配bean,如下:
@Bean @ConditionalOnBean(name="user") public Runnable createRunnable(){ return () -> {}; }
@Component class User{}
备注:此时会装配Bean,如果去掉User的Bean,则不会装配Bean
4、@ConditionalOnMissingBean:当参数Bean不存在时才装配Bean