【问题标题】:How to use @ConstructorBinding and @PropertySource together with @ConfigurationProperties with in Spring Boot 2.2.4?如何在 Spring Boot 2.2.4 中使用 @ConstructorBinding 和 @PropertySource 以及 @ConfigurationProperties?
【发布时间】:2020-06-09 02:36:42
【问题描述】:

我是 Spring Boot 的新手。目前,我正在尝试创建一个 POJO 类 (SystemProperties.class) 来读取属性文件中的值(parameter.properties 与 application.properties 分开但仍在同一目录/src/main/resources。当我在类中使用@ConstructorBinding 以使其不可变时,就会出现问题。

  • @ConstructorBinding 需要与@EnableConfigurationProperties 或@ConfigurationPropertiesScan 一起使用。
  • @ConfigurationPropertiesScan 将忽略使用@PropertySource 指定外部时需要的@Configuration 注释
    *.properties 文件。

A) SystemProperties.class

@Configuration
@PropertySource("classpath:parameter.properties")

@ConstructorBinding
@ConfigurationProperties(prefix = "abc")
public class SystemProperties {

    private final String test;

    public SystemProperties (
            String test) {
        this.test = test;
    }

    public String getTest() {
        return test;
    }

B) parameter.properties

abc.test=text1

我已尝试删除 @PropertySource 注释,但无法检索该值,除非它来自 application.properties。非常感谢任何帮助!

【问题讨论】:

    标签: java spring spring-boot immutability


    【解决方案1】:

    解决这个问题的方法是将类分成两个具有两个不同关注点的类。使用这样的解决方案,您可以保留您创建的 SystemProperties 类,并另外添加另一个类,仅用于加载属性文件参数以使它们可用于您的应用程序。

    解决办法如下:

    @ConstructorBinding
    @ConfigurationProperties(prefix = "abc")
    public class SystemProperties {
    
        private final String test;
    
        public SystemProperties(
                String test) {
            this.test = test;
        }
    
        public String getTest() {
            return test;
        }
    }
    

    请注意,我省略了 @Configuration@PropertySource 注释。

    @Configuration
    @PropertySource("classpath:parameter.properties")
    public class PropertySourceLoader {
    }
    

    请注意,我只是在一个新类上添加了这个注释,专门用于加载属性文件。

    最后,您可以在主应用程序类中添加@ConfigurationPropertiesScan 以启用属性映射机制。

    【讨论】:

    猜你喜欢
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 2019-12-15
    相关资源
    最近更新 更多