首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring - ConfigurationProperties用法

Spring - ConfigurationProperties用法
EN

Stack Overflow用户
提问于 2019-10-07 07:59:57
回答 1查看 152关注 0票数 0

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

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

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

代码语言:javascript
复制
@Component
public class FirstClient implements Client {

    private String hello;
    public FirstClient(@Value("hello.first") String hello) {
        this.hello = hello;
    }
    // do some stuff with hello
}
代码语言:javascript
复制
@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背景”的我发现,在前面提到的任何代码操作中神奇地使用注释有点问题。

我的第二种方法是介绍配置类:

代码语言:javascript
复制
@ConfigurationProperties(prefix = "hello")
public class DummyProperties {

    private String first;
    private String second;

    // get/set omitted
}
代码语言:javascript
复制
public class FirstClient implements Client {

    private String hello;

    public FirstClient(String hello) {
        this.hello = hello;
    }
    // do some stuff with hello
}
代码语言:javascript
复制
public class SecondClient implements Client {

    private String hello;

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

加入逻辑是:

代码语言:javascript
复制
@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());
        }
    }
}

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

有什么建议或补充意见吗?

EN

回答 1

Stack Overflow用户

发布于 2019-10-07 08:55:58

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

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58265523

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档