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
}
How can I get the proper path to the rm.properties file and pass it to the bean at runtime?
Edit: Added constructor code.
Edit: 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.FileandFileReaderonly 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:
Replace this:
with something like this:
Better yet, use Spring’s
Resourceabstraction, by declaring the constructor parameter asorg.springframework.core.io.Resource:When you then supply the path:
Spring will automatically create a
ClasspathResourcefor that path (using a classpath) , and pass it to your constructor.