如何在运行时获取属性文件的路径并将其传递给Bean [英] How to get the path to a properties file and pass it to a bean at runtime
问题描述
我有一个由Spring创建的bean.实际的类与Spring驻留在不同的JAR中.该bean被传递了一个路径作为构造函数参数.但是,我在检索文件句柄时遇到困难.该文件位于WEB-INF/classes/中.我已经尝试过基于WEB-INF的相对路径,但是显然那是行不通的.
I have a bean that is created by Spring. The actual class resides in a different JAR than Spring. This bean is passed a path as a constructor argument. However, I am having difficulty retrieving a handle to the file. The file is in WEB-INF/classes/. I've tried relative pathing based on WEB-INF, but obviously that didn't work.
XML:
<bean id="configurationManager" class="package.ConfigurationManager"
scope="singleton">
<property name="configurationMapping">
<bean class="package.PropertiesFileConfigurationMapper">
<constructor-arg type="java.lang.String">
<value>/path/to/file</value>
</constructor-arg>
</bean>
</property>
</bean>
Bean:
public class ConfigurationMapper {
public ConfigurationMapper(String resource) {
_map = new HashMap<String, String>();
String property = null;
BufferedReader reader = null;
try {
FileReader file = new FileReader(resourcePath);
reader = new BufferedReader(file);
while ((property = reader.readLine()) != null) {
if (property.matches("(.+)=(.+)")) {
String[] temp = property.split("(.+)=(.+)");
_map.put(temp[0], temp[1]);
}
}
} catch (Exception ex){
ex.printStackTrace();
} finally {
if (reader != null)
reader.close();
}
}
//other methods to manipulate settings
}
如何获取rm.properties
文件的正确路径,并在运行时将其传递给Bean?
How can I get the proper path to the rm.properties
file and pass it to the bean at runtime?
添加了构造函数代码.
我明白了.我将构造函数参数更改为不再采用路径.现在需要一个资源,因此Spring已经找到了我想要加载的资源.
I got it. I changed the constructor argument to no longer take a path. It now takes a Resource, so Spring has found the resource that I wanted loaded.
推荐答案
java.io.File
和FileReader
仅适用于实际文件.打包在JAR文件中的资源本身不是文件.
java.io.File
and FileReader
only work for actual files. A resource packed inside a JAR file isn't itself a file.
最简单的加载方法是作为类路径资源:
The easiest way to load it is as a classpath resource:
替换此:
FileReader file = new FileReader(resourcePath);
reader = new BufferedReader(file);
具有这样的内容:
InputStream inputStream = getClass().getResourceAsStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
更好的是,通过将构造函数参数声明为org.springframework.core.io.Resource
:来使用Spring的Resource
抽象:
Better yet, use Spring's Resource
abstraction, by declaring the constructor parameter as org.springframework.core.io.Resource
:
public ConfigurationMapper(Resource resource) {
...
InputStream inputStream = resource.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
然后提供路径:
<constructor-arg value="classpath:/path/to/file"/>
Spring将为该路径自动创建一个ClasspathResource
(使用类路径),并将其传递给您的构造函数.
Spring will automatically create a ClasspathResource
for that path (using a classpath) , and pass it to your constructor.
这篇关于如何在运行时获取属性文件的路径并将其传递给Bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!