简体   繁体   中英

Unable to load application.properties file

What path should I be putting in here to load this .properties file? I can't seem to get it to load...

InputStream stream = ProductVersionService.class.getResourceAsStream("/application.p‌​roperties");
properties.load(stream);

在此处输入图片说明

您需要指定从根到文件本身的属性文件的完整路径: /main/resources/application.properties

I could see, you are using Maven to build this project and hence your final jar wont have src/main/resource or src/main/java either. All of these directories will be removed and all the contents beneath it will be added to root of jar and hence referring the path using src/main/* will result into an error. You should make use of

Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties")

Properties prop = new Properties();
prop.load(PropertiesUtil.class.getClassLoader().getResourceAsStream("/main/resources/application.properties"));

Since your properties files will be read from war package, easiest solution would be to load them as a ResourceBundle :

ResourceBundle resourceBundle = ResourceBundle.getBundle("main.resources.application");
String prop = resourceBundle.getString("nameofproperty");
System.out.println(prop);

No need to develop something custom.

If you follow Spring architecture you can use this class:

org.springframework.core.io.support.PropertiesLoaderUtils

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM