5

Please can you help me to read the properties from application.properties file in Spring Boot, without autowiring the Environment and without using the Environment?

No need to use ${propname} either. I can create properties object but have to pass my properties file path. I want to get my prop file from another location.

OrangeDog
  • 36,653
  • 12
  • 122
  • 207
Braj
  • 81
  • 1
  • 1
  • 2

7 Answers7

15

This is a core Java feature. You don't have to use any Spring or Spring Boot features if you don't want to.

Properties properties = new Properties();
try (InputStream is = getClass().getResourceAsStream("application.properties")) {
  properties.load(is);
}

JavaDoc: http://docs.oracle.com/javase/8/docs/api/java/util/Properties.html

OrangeDog
  • 36,653
  • 12
  • 122
  • 207
  • 1
    For me "is" was always null. Helped me to adjust the code like this: getClass().getClassLoader().getResourceAsStream("application.properties") – ironix Apr 21 '23 at 15:03
  • The loader you have to use depends on what environment you're in. – OrangeDog Apr 21 '23 at 16:44
13

OrangeDog solution didn't work for me. It generated NullPointerException.

I've found another solution:

ClassLoader loader = Thread.currentThread().getContextClassLoader();
Properties properties = new Properties();
try (InputStream resourceStream = loader.getResourceAsStream("application.properties")) {
    properties.load(resourceStream);
} catch (IOException e) {
    e.printStackTrace();
}
Vladislav Kysliy
  • 3,488
  • 3
  • 32
  • 44
  • That works for me, but I've got returned value like: ${TIME_ZONE_ID:UTC}, while line in application.properties is: time.zoneId=${TIME_ZONE_ID:UTC}. Any idea how to read correct value? – Magda Aug 10 '21 at 13:02
  • @Magda is it something like this? https://stackoverflow.com/questions/48575426/spring-create-localdate-or-localdatetime-from-value-parameter – Vladislav Kysliy Aug 11 '21 at 09:17
2

Try to use plain old Properties.

final Properties properties = new Properties();
properties.load(new FileInputStream("/path/config.properties"));
System.out.println(properties.getProperty("server.port"));

In case you need to use that external properties file in your configuration it can be accomplished with @PropertySource("/path/config.properties")

Bohdan Levchenko
  • 3,411
  • 2
  • 24
  • 28
2

The following code extracts the environment value from an existing application.properties file which is located in the Deployed Resources under WEB-INF/classes :

    // Define classes path from application.properties :
    String environment;
    InputStream inputStream;
    try {
        // Class path is found under WEB-INF/classes
        Properties prop = new Properties();
        String propFileName = "com/example/project/application.properties";

        inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
        // read the file
        if (inputStream != null) {
            prop.load(inputStream);
        } else {
            throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
        }

        // get the property value and print it out
        environment = prop.getProperty("environment");

        System.out.println("The environment is " + environment);
    } catch (Exception e) {
        System.out.println("Exception: " + e);
    }

Here is example, running the above code with the following input from the application.properties (Text file):

# Application settings file
environment=Test
release_date=DATE
session_timeout_minutes=25
## Allowable image types
img_file_extensions="jpeg;pjpeg;jpg;png;gif"
## Images are saved with this extension
img_default_extension=jpg
# Mail Settings / Addresses
mail_debug=false
Output:

The environment is Test
Supercoder
  • 1,066
  • 1
  • 10
  • 16
1

To read application.properties just add this annotation to your class:

@ConfigurationProperties
public class Foo { 
}

If you want to change the default file

@PropertySource("your properties path here")
public class Foo { 
}
Smaniotto
  • 404
  • 4
  • 16
1

If everything else is properly set, you can the annotation @Value. Springboot will take care of loading the value from property file.

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.beans.factory.annotation.Value;

@Configuration
@PropertySource("classpath:/other.properties")
public class ClassName {
  @Value("${key.name}")
  private String name;
}
Abbin Varghese
  • 2,422
  • 5
  • 28
  • 42
0

Adding to Vladislav Kysliy's elegant solution, below code can be directly plugged as REST API Call to get all the key/value of application.properties file in Spring Boot without knowing any key. Additionally, If you know the Key you can always use @Value annotation to find the value.

@GetMapping
@RequestMapping("/env")
public java.util.Set<Map.Entry<Object,Object>> getAppPropFileContent(){
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    java.util.Properties properties = new java.util.Properties();
    try(InputStream resourceStream = loader.getResourceAsStream("application.properties")){
        properties.load(resourceStream);
    }catch(IOException e){
        e.printStackTrace();
    }
    return properties.entrySet();
}