3

I want to load Properties Files in Java code. But I use profile to config -Dspring.profiles.active=local or dev... How to load properties files by profile Something like this:

classpath:${spring.profiles.active}/test.properties

How to do that in Java code ? I did as below, but get null.

Properties prop = new Properties();
InputStream iStream = Helper.class.getClassLoader().getResourceAsStream("test.properties");
    try {
        prop.load(iStream);
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    } finally {
        try {
            iStream.close();
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }
Jerry
  • 185
  • 1
  • 6
  • 18
  • Possible duplicate of [Environment Specific application.properties file in Spring Boot application](http://stackoverflow.com/questions/32196451/environment-specific-application-properties-file-in-spring-boot-application) – Bond - Java Bond Apr 07 '17 at 06:20
  • But I use getResourceAsStream() to load, it cannot get that file – Jerry Apr 07 '17 at 08:09
  • Well you can't mix spring feature of `profiles` with plain file loading. The feature is available out-of-box in Spring boot which can be easily leveraged (*refer question to which I marked this as duplicate in earlier comment*) – Bond - Java Bond Apr 07 '17 at 09:41
  • Thank for your suggest. However, I have not solved my problem yet. I do not use spring boot, I used -Dspring.profiles.active=local to configure argument on Tomcat, but it cannot load properties by getResourceAsStream(), InputStream still null. My properties file is in src/main/resources/local/test.properties – Jerry Apr 09 '17 at 16:20

2 Answers2

0

This is some working code for us:

String activeProfile = System.getProperty("spring.profiles.active");
InputStream workSpacesFIS = this.getClass().getClassLoader()
        .getResourceAsStream(activeProfile + "/customers.txt");
if (workSpacesFIS != null) { ...
Ardent Coder
  • 3,777
  • 9
  • 27
  • 53
0

Loading Java Properties Files by Profile

public Properties getProp() throws IOException {
        final Properties prop = new Properties();
        prop.load(TestService.class.getResourceAsStream("/application.properties"));
        String activeProfile = prop.getProperty("spring.profiles.active");
        prop.load(TestService.class.getResourceAsStream("/application-"+activeProfile+".properties"));
        return prop;

    }
ngg
  • 1,493
  • 19
  • 14