使用spring获取当前工作目录

时间:2013-05-20 09:10:30

标签: java spring

这是在运行时获取Java应用程序的当前工作目录的代码。

String currentWorkingDirectory = System.getProperty("user.dir")+System.getProperty("file.separator");

有没有办法使用spring-context xml配置它。

例如:

<bean id="csvReportGenerator" class="some.path.CSVReportGenerator">  
<constructor-arg name="outputFileName" value="${currentWorkingDirectory}/${reportOutputFileGeneric}"/>
</bean>

3 个答案:

答案 0 :(得分:7)

是的,您可以使用Spring表达式来完成它。请参阅this文章

的第6.4.1节
<property name="userDir" value="#{ systemProperties['user.dir'] }"/>
<property name="fileSep" value="#{ systemProperties['file.separator'] }"/>

答案 1 :(得分:0)

如果要在unix环境(通常是)中进行部署,则可以使用classpath:或使用./。说,classpath:sample.properties./sample.properties

答案 2 :(得分:0)

spring-context.xml中您可以使用

1)classpath:filename.properties

2)./filename.properties

3)file:./

对于context-xml的当前目录,./应该有效,但对于工作目录,file:./可以正常工作。

例如

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <context:annotation-config />

    <bean id="properties"
        class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="singleton" value="true" />
        <property name="ignoreResourceNotFound" value="true" />
        <property name="locations">
            <list>
                <value>classpath:/shaharma.properties</value>
                <value>./shaharma-custom.properties</value>
            </list>
        </property>
    </bean>

</beans>