简体   繁体   中英

How to use @ConstructorBinding and @PropertySource together with @ConfigurationProperties with in Spring Boot 2.2.4?

I am new to Spring Boot. Currently, I am trying to create a POJO class ( SystemProperties.class ) to read the value in a properties file ( parameter.properties separate from application.properties but still under the same directory /src/main/resources. The issue happens when I am using the @ConstructorBinding in the class in order for it to be immutable.

  • @ConstructorBinding needs to be used with @EnableConfigurationProperties or @ConfigurationPropertiesScan.
  • @ConfigurationPropertiesScan will ignore @Configuration annotation which is needed when using @PropertySource to specify external
    *.properties file.

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

I have tried to remove the @PropertySource annotation but the value cannot be retrieved unless it is from the application.properties. Any help is greatly appreciated!

The way to solve this is to split the class into two classes with two different concerns. With such solution, you retain the SystemProperties class you created and additionally add another class simply for loading the properties file parameters to make them available to your application.

The solution would be as follows:

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

    private final String test;

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

    public String getTest() {
        return test;
    }
}

Notice that I have omitted the @Configuration and @PropertySource annotations.

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

Notice I have simply added this annotations on a new class, solely created to load the properties file.

Finally, you can add @ConfigurationPropertiesScan on your main application class to enable the property mapping mechanism.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM