首页 > 解决方案 > Spring - ConfigurationProperties 用法

问题描述

目前,我正在开发一个使用 Spring 配置的项目,但遇到了设计问题。

我在下面发布了一个简化的代码段。

假设我的应用程序有 2 个客户端,它们是 Spring@Component并用于@Value注入配置值。

@Component
public class FirstClient implements Client {

    private String hello;
    public FirstClient(@Value("hello.first") String hello) {
        this.hello = hello;
    }
    // do some stuff with hello
}
@Component
public class SecondClient implements Client {

    private String hello;
    public SecondClient(@Value("hello.second") String hello) {
        this.hello = hello;
    }
    // do some stuff with hello
}

通过使用这种方法,我可以轻松地@Autowire新建 Spring 组件。但是,来自“非 Spring 背景”,我发现神奇地将前面提到的注释用于任何代码操作都有些问题。

我的第二种方法是引入配置类:

@ConfigurationProperties(prefix = "hello")
public class DummyProperties {

    private String first;
    private String second;

    // get/set omitted
}
public class FirstClient implements Client {

    private String hello;

    public FirstClient(String hello) {
        this.hello = hello;
    }
    // do some stuff with hello
}
public class SecondClient implements Client {

    private String hello;

    public SecondClient(String hello) {
        this.hello = hello;
    }
    // do some stuff with hello
}

加入逻辑将是:

@Component
@EnableConfigurationProperties(DummyProperties.class)
public class ClientCreator {

    private DummyProperties props;
    public ClientCreator(DummyProperties props) {
        this.props = props;
    }

    public Client create(boolean isSatisfied) {
        // some custom check logic
        if (isSatisfied) {
            return new FirstClient(props.getFirst());
        } else {
            return new SecondClient(props.getSecond());
        }
    }
}

然而,这并不一定需要是一个好的流程。

有什么建议或其他想法吗?

标签: javaspringconfiguration

解决方案


您可以使用上述注释或@PropertySource 等在配置类或主应用程序类的开头指定配置属性文件位置的位置,


推荐阅读