【问题标题】:Read properties file from WEB-INF folder从 WEB-INF 文件夹中读取属性文件
【发布时间】:2014-12-07 18:24:47
【问题描述】:
我想从 WEB-INF 文件夹而不是类路径中读取属性文件,因为如果我进行任何修改,我不想再次编译我的应用程序。我的文件正在目录中构建,但是当我尝试访问时,它没有显示任何内容。请任何人都可以帮我解决这个问题。我正在使用 Spring 框架。因此,如果 Spring 中有任何方法可以让我们不需要一次又一次地编译我们的应用程序,并且修改由应用程序自己承担。
【问题讨论】:
标签:
java
eclipse
spring
properties-file
web-inf
【解决方案1】:
您可以将属性文件放在资源文件夹中。它不需要重新编译应用程序。
在 spring 中,您可以使用以下几行从属性文件中读取属性值:
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:dash_conf.properties</value>
</list>
</property>
</bean>
另外,如果你想从 java 类中读取属性文件,你可以使用:
InputStream in = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(fileName);
Properties prop = new Properties();
prop.load(in);
希望这能解决您的问题。
【解决方案2】:
将此添加到您的应用程序上下文配置文件中并尝试。
<bean id="applicationProperties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>yourPropertiesFile.properties</value>
</list>
</property>
</bean>
要从属性文件中访问属性,请在您的类中使用 bean 的 ID,该 ID 必须使用 @Service 或 @Component 进行注释
@Resource(name="applicationProperties")
private Properties anyVariableName;
...
...
String propValue = anyVariableName.getProperty("propertyName");