我应该在此处放置什么路径来加载此.properties
文件?好像加载不出来。。。
InputStream stream = ProductVersionService.class.getResourceAsStream("/application.properties");
properties.load(stream);
我应该在此处放置什么路径来加载此.properties
文件?好像加载不出来。。。
InputStream stream = ProductVersionService.class.getResourceAsStream("/application.properties");
properties.load(stream);
Properties prop = new Properties();
prop.load(PropertiesUtil.class.getClassLoader().getResourceAsStream("/main/resources/application.properties"));
我可以看到,您正在使用 Maven 来构建这个项目,因此您的最终 jar 也不会有 src/main/resource 或 src/main/java。所有这些目录都将被删除,并且它下面的所有内容都将添加到 jar 的根目录中,因此使用 src/main/* 引用路径将导致错误。你应该利用
Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties")
您需要指定属性文件的完整路径,从根目录到文件本身:/main/resources/application.properties
无需开发定制的东西。
如果您遵循 Spring 架构,则可以使用此类:
org.springframework.core.io.support.PropertiesLoaderUtils
由于您的properties
文件将从war
包中读取,因此最简单的解决方案是将它们加载为ResourceBundle
:
ResourceBundle resourceBundle = ResourceBundle.getBundle("main.resources.application");
String prop = resourceBundle.getString("nameofproperty");
System.out.println(prop);