使用Spring获取当前工作目录

7

以下是获取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>

这可能会有所帮助 https://dev59.com/G2865IYBdhLWcg3wIrFg - seenukarthi
3个回答

8
是的,你可以使用Spring表达式来实现。请参阅这篇文章的6.4.1节。
<property name="userDir" value="#{ systemProperties['user.dir'] }"/>
<property name="fileSep" value="#{ systemProperties['file.separator'] }"/>

1
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>

1
您可以简单地使用classpath:或者在Unix环境中(通常是这样)使用./。例如:classpath:sample.properties./sample.properties

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接