@Value is not taking value from specified @PropertySource when two properties files have same key

44 Views Asked by At

I am trying to create two classes to fetch configuration values from two different properties file (application-e1.properties and application-e2.properties).

application-e1.properties =>

param=e1Test

application-e2.properties =>

param=e2Test

I have created 2 classes EmployeeDev and EmployeeTest to read from respective files:

@Component
@PropertySource("classpath:application-e1.properties")
public class EmployeeDev {

    @Value("${param}")
    String param;

    public String getParam() {
        return param;
    }

    public void setParam(String param) {
        this.param = param;
    }
}
@Component
@PropertySource("classpath:application-e2.properties")
public class EmployeeTest {

    @Value("${param}")
    String param;

    public String getParam() {
        return param;
    }

    public void setParam(String param) {
        this.param = param;
    }
}

Whenever I call EmployeeDev or EmployeeTest, it is always returning param value as e2Test.

I am trying to create the configuration of 2 profiles at a time here. Can anyone help me through this?

1

There are 1 best solutions below

0
Slevin On

According to Spring's Documentation this is what @PropertySource does:

Annotation providing a convenient and declarative mechanism for adding a PropertySource to Spring's Environment. To be used in conjunction with @Configuration classes.

In certain situations, it may not be possible or practical to tightly control property source ordering when using @PropertySource annotations. For example, if the @Configuration classes above were registered via component-scanning, the ordering is difficult to predict. In such cases — and if overriding is important — it is recommended that the user fall back to using the programmatic PropertySource API.

So all this annotation does is adding a specific property source to the existing environment.

What your code does is, it combines the two sources application-e1.properties and application-e2.properties by merging the properties into one environment, while the later properties overide the prior ones. You now have an Environment where param=e2Test is set. Adding already existing property sources are not predictably in terms of overriding.

What you should do is having different Profiles which have their properties set in their related property files and then activate the profiles you need. If you wanna set differents specific params for different usecases within one and the same profile you have to name them separately.