【问题标题】:Spring Boot @ConfigurationProperties correct usageSpring Boot @ConfigurationProperties 正确用法
【发布时间】:2015-05-06 10:06:21
【问题描述】:

我们实际上使用 Spring Boot 的 @ConfigurationProperties 作为基本的配置映射器:它为我们提供了一个简单的快捷方式来映射对象的属性。

@ConfigurationProperties("my.service")
public class MyService {
    private String filePrefix;
    private Boolean coefficient;
    private Date beginDate;
    // getters/setters mandatory at the time of writing

    public void doBusinessStuff() {
        // ...
    }
}

虽然这在我们为应用程序设计原型时大大提高了生产力,但我们开始质疑这是否正确使用。

我的意思是,配置属性在 Spring Boot 的上下文中具有不同的状态,它们通过执行器端点公开,它们可用于触发条件 bean,并且似乎更倾向于技术配置属性。

问题:在任何商业财产/价值上使用这种机制是否“正确”,还是完全滥用?

我们错过了任何潜在的缺点吗?

现在我们唯一担心的是我们不能在不可变类上使用@ConfigurationProperties,这与Spring Boot的跟踪器上的这个问题密切相关:Allow field based @ConfigurationProperties binding

【问题讨论】:

    标签: java configuration spring-boot


    【解决方案1】:

    如果您的属性表示可根据环境/配置文件进行配置的内容,那么该机制就是用于此目的。虽然我有点不清楚你的意思 “映射对象的属性”。

    我一般不赞成这种风格,特别是如果你的 bean 有多个属性要设置。一个更标准的习惯用法是拥有一个封装用于创建 bean 的属性/设置的类:

    @ConfigurationProperties("my.service")
    public class MyServiceProperties {
        private String filePrefix;
        private Boolean coefficient;
        private Date beginDate;
        // getters/setters mandatory at the time of writing   
    }
    

    那么您的服务类将如下所示:

    @EnableConfigurationProperties(MyServiceProperties.class)
    public class MyService {
        @Autowired
        private MyServiceProperties properties;
        //do stuff with properties
    
        public void doBusinessStuff() {
            // ...
        }
    }
    

    这至少允许您通过它的构造函数轻松地将属性传递给不可变类(复制任何可变属性)。如果您发现应用程序的其他部分需要一些共享配置,也可以重用属性 bean。

    【讨论】:

    • 谢谢,我们确实使用了专用于配置属性的类,示例被简化了。一些业务价值可能不依赖于环境,它们只是外部化的业务属性。我们通常使用 @Value 来注入 props,但 @ConfigurationProperties 是一种方便的快捷方式,可以用最少的样板注入一堆 props。但是,当您查看 Spring Boot 的内部结构时,ConfigurationProperties 不仅仅是您的普通道具。这有点像劫持技术机制,所以我们开始质疑我们使用的正确性。
    猜你喜欢
    • 1970-01-01
    • 2015-06-17
    • 2018-02-07
    • 2016-07-24
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    相关资源
    最近更新 更多