Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read application.properties file without Environment

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.

like image 508
Braj Avatar asked Jun 12 '17 12:06

Braj


People also ask

How do I read application properties file?

One of the easiest ways to read a property from the application. properties file is by autowiring an Environment object. All you need to do is to use the @Autowired annotation. It is called dependency injection.

What is the alternative to application properties file?

YAML is a convenient format for specifying hierarchical configuration data. This can be more readable than its property file alternative since it does not contain repeated prefixes.


2 Answers

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

like image 102
OrangeDog Avatar answered Oct 18 '22 22:10

OrangeDog


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();
}
like image 12
Vladislav Kysliy Avatar answered Oct 18 '22 22:10

Vladislav Kysliy