【问题标题】:How to declare an optional @Bean in Spring?如何在 Spring 中声明一个可选的 @Bean?
【发布时间】:2018-06-20 10:05:46
【问题描述】:

我想在我的@Configuration 文件中提供一个可选的@Bean,例如:

@Bean
public Type method(Type dependency) {
    // TODO
}

当找不到依赖时,不应该调用该方法。

怎么做?

【问题讨论】:

标签: spring javabeans


【解决方案1】:

如果在Spring中使用SpringBootConditional,则需要使用ConditionalOnClasssince 4.0See If using Spring

SpringBoot 的示例:-

@Bean
@ConditionalOnClass(value=com.mypack.Type.class)
public Type method() {
    ......
    return ...
}

现在只有当com.mypack.Type.classclasspath 中时才会调用method()

【讨论】:

    【解决方案2】:

    除了接受的答案之外,您还必须在调用任何需要该依赖项的方法之前检查依赖项是否已初始化。

    @Autowired(required = false) 
    Type dependency;
    
    public Type methodWhichRequiresTheBean() {
       ...
    }
    
    public Type someOtherMethod() { 
         if(dependency != null) { //Check if dependency initialized
             methodWhichRequiresTheBean();
         }
    } 
    

    【讨论】:

    • 这不是提供一个 Bean
    猜你喜欢
    • 2019-02-27
    • 2013-08-05
    • 1970-01-01
    • 1970-01-01
    • 2011-01-05
    • 1970-01-01
    • 2012-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多