开发者

spring folder content resource injected in bean

开发者 https://www.devze.com 2023-01-21 22:23 出处:网络
I need to pass a folder (java.io.File) as a function parameter. I tried to just declare the location of the folder, but it looks in SERVER_HOME (/home/user/tomcat).

I need to pass a folder (java.io.File) as a function parameter.

I tried to just declare the location of the folder, but it looks in SERVER_HOME (/home/user/tomcat).

So my next try is to inject a File (directory) which is located in WEB-INF/myFolder.

my first try failed:

<bean name="path" class="java.io.File">  
    <constructor-arg value="classpath:WEB-INF/myFolder" />  
</bean>

But it looks for /home/user/tomcat/classpath:WEB-INF/myFolder

I've been messing around but I can't figure o开发者_C百科ut how to do it.

Any help or advice would be great.

Thank you all!


You are not supposed to access the file system from a webapp, especially not to make assumptions about the webapps own file representation. WEB-INF/myfolder may or may not be a directory, depending if you are dealing with a WAR (no) or an exploded WAR (yes). If you absolutely need a file system resource, try to acquire it using System.getPreference("java.io.tmpdir").


OK, here are a few hints:

Use a Factory bean to retrieve the File. Let it

  1. Create a temporary directory
  2. Extract the contents of the jar to that temporary directory
  3. return the temporary directory in it's getObject() method

Then inject the factory bean into your bean:

<!-- This is a Factorybean that creates a file -->
<bean class="com.yourcompany.ConfigFolderCreator" id="configDir">
    <property name="packageToUnpack" value="com.yourcompany.yourpackage" />
</bean>

<bean class="com.your.legacy.Api">
     <!-- inject the factory bean instead of a file -->
     <property name="configFolder" ref="configDir" />
</bean>


You could use spring's FileSystemResource class

<bean id="bean" class="org.springframework.core.io.FileSystemResource">
        <constructor-arg><value>your.file</value></constructor-arg>
</bean>
0

精彩评论

暂无评论...
验证码 换一张
取 消