Search code examples
spring-bootconfiguration-filesspring-annotations

Restricting @PropertySource to specific @Configuration classes in spring


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?


Solution

  • 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")