Spring Boot基于特定条件创建Bean例子 : ConditionalOnClass

结合使用注解@ConditionalOnClass和@Bean,可以仅当某些类存在于 classpath 上时候才创建某个Bean:

@Configuration
public class ConditionOnClassConfig {

    @Bean
    @ConditionalOnClass(value={java.util.HashMap.class})
    public A beanA(){
        // 仅当类 java.util.HashMap 存在于 classpath 上时才创建一个bean : beanA
        // 注意这里使用了 @ConditionalOnClass 的属性value,
        return new A(); 
    }

    @Bean
    @ConditionalOnClass(name="com.sample.Dummy")
    public B beanB(){
        // 仅当类 com.sample.Dummy 存在于 classpath 上时才创建一个bean : beanB
        // 注意这里使用了 @ConditionalOnClass 的属性 name,
        return new B(); 
    }        
}


  • 什么时候使用 name,什么时候使用 value ?
    • name : 不确定指定类在classpath
    • value : 确定指定类在 classpath

Use the name attribute in case if you want to specify the class name and you are not sure whether the classes will be available on the classpath and use value when the classes are available on the classpath.
注解ConditionalOnClass官方API文档

猜你喜欢

转载自blog.csdn.net/andy_zhang2007/article/details/81284875
今日推荐