【问题标题】:What is the best way to select bean implementation from application.yaml从 application.yaml 中选择 bean 实现的最佳方法是什么
【发布时间】:2022-02-05 12:33:11
【问题描述】:

我有一个 Spring Boot 应用程序,我想在其中自动装配一个在 application.yaml 中指定实现的 bean。实现它的最佳方法是什么?

@Component
public class FooFormatter implements Formatter {}

@Component
public class BarFormatter implements Formatter {}

public class MyService {
    @Autowired
    @Qualifier("value_from_config")// The implementation is specified in application.yaml file
    private Formatter formatter;
}

【问题讨论】:

标签: spring spring-boot


【解决方案1】:

实现它的最佳方法是使用@ConditionalOnProperty

所以给出以下几点:

@Component
@ConditionalOnProperty(prefix = "app.formatter", name = "impl", havingValue = "foo",matchIfMissing = true)  
public class FooFormatter implements Formatter {

}

@Component
@ConditionalOnProperty(prefix = "app.formatter", name = "impl", havingValue = "bar")    
public class BarFormatter implements Formatter {

}

然后要仅启用FooFormatter,请将应用程序属性配置为:

app.formatter.impl=foo

要仅启用BarFormatter,请将应用程序属性配置为:

app.formatter.impl=bar

如果应用程序属性中没有定义app.formatter.impl,它将默认为FooFormatter(因为matchIfMissing = true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-26
    • 1970-01-01
    • 2019-05-30
    • 2021-06-29
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多