4

I have the following property files:

  • application.properties - Base spring config
  • common.properties - Common config
  • servicea.properties - Service specific config
  • password.properties - Password Config

Based on the last three files, I have 3 <Name>Property classes in the following format.

@Configuration
@PropertySource("file:<filepath>")
public class ServiceAProperties {

    private final Environment env;

    @Autowired
    public ServiceAProperties (Environment env) {
        this.env = env;
    }

    public String getTest() {
        String test = env.getProperty("application.test"); // Accessible - Not Intended
        test = env.getProperty("common.test");             // Accessible - Not Intended
        test = env.getProperty("servicea.test");           // Accessible - Intended
        test = env.getProperty("password.test");           // Accessible - Not Intended
        return env.getProperty("servicea.test");
    }
}

For some reason even though I only have the respective Property classes marked with their specific property file paths, they are also picking up paths from other files and adding it to the env.

How can I make sure that I my environment to be generated only from the files I specify?

shadoweye14
  • 773
  • 2
  • 7
  • 22

2 Answers2

2

The spring docs for @PropertySource says:

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

This means that there is only one Spring Environment. When you have multiple classes annotated with this annotation they will always contribute to the same environment because there is only one.

So, to answer your question, in your case the environment will always be filled with data from all classes that have @Configuration and @PropertySource annotations.

In order to fill the environment with data that you specify, you can use profile specific properties. You can separate the data in multiple profiles and choose the profiles that will be activated (and which data will be accessible in the environment).

Dimitar Spasovski
  • 2,023
  • 9
  • 29
  • 45
  • Thanks, but multiple profiles do not solve the problem for me. Multiple profiles still load all the profiles into the environment. In addition to the fact that I will not be able to access the other profiles that are not 'active'. – shadoweye14 May 05 '18 at 02:05
0

I am sharing my own solution to this since I was not able to find an acceptable answer.

Using a new ResourcePropertySource("classpath:<location>") allows you to load in multiple individual property files using their respective individual objects.

Once loaded, the configuration can be accessed in the same way as before propertiesObj.getProperty("propKey")

shadoweye14
  • 773
  • 2
  • 7
  • 22