【问题标题】:Access properties set in settings.xml to spring.xml访问settings.xml中设置的属性到spring.xml
【发布时间】:2014-04-02 07:45:40
【问题描述】:

我在user_directory/.m2 文件夹中有一个settings.xml 文件。我在settings.xml 中设置了一个属性。我希望它在spring.xml 中访问它。

设置.xml

<profiles>
    <profile>
    <id>default</id>
    <activation>
        <activeByDefault>true</activeByDefault>
    </activation>
    <properties>
        <testName>Test</testName>
    </properties>
    </profile>      
</profiles>

在我写的 pom.xml 中

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

我是否必须在 src/main/resources 文件夹中创建 test.properties 文件。

name = ${testName}

spring.xml我用它作为

<context:property-placeholder location="classpath:src/main/resources/test.properties"/>
<bean class="java.lang.String" id="nameTest">
    <constructor-arg value="name"/>
</bean> 

当run.Exception是

线程“main”中的异常 org.springframework.beans.factory.BeanInitializationException:可以 不加载属性;嵌套异常是 java.io.FileNotFoundException:类路径资源 [src/main/resources/test.properties] 无法打开,因为它确实如此 不存在

出了什么问题。如何访问从settings.xmlspring.xml 的属性。

【问题讨论】:

    标签: java spring maven properties-file


    【解决方案1】:

    您错误地配置了属性占位符。 src/main/resource 不在你的类路径中,你应该放一些类似的东西:

    <context:property-placeholder location="classpath:test.properties"/>
    

    对于上下文的配置,您可以:

    一个。直接过滤你的 spring 上下文:

    <bean class="java.lang.String" id="nameTest">
        <constructor-arg value="${testName}"/>
    </bean> 
    

    b.或者过滤您的 test.properties 配置文件,然后将其作为属性占位符注入到您的 spring.xml 中:

    test.properties:

    spring.testName=${testName}
    

    spring.xml:

    <context:property-placeholder location="classpath:test.properties"/>
    
    <bean class="java.lang.String" id="nameTest">
        <constructor-arg value="${spring.testName}"/>
    </bean> 
    

    【讨论】:

      【解决方案2】:

      我看到的几点:

      1. property-placeholder 的 location 属性引用类路径上的文件,但您想使用文件系统上的文件,所以它必须是这样的:

        <context:property-placeholder location="file:///user_directory/.m2/settings.properties"/>
        
      2. 您的设置文件是 XML。默认情况下所期望的实际上是 Java 属性格式的文件。可能有使用自定义 XML 的方法,但我对此并不熟悉。所以你的 XML 文件会翻译成这样:

        profile.id = default
        profile.activation.activateByDefault = true
        profile.properties.testName = Test
        ...
        
      3. 稍后在您的spring.xml 中引用您的属性时,您只需使用${profile.id} 来放置settings.properties 文件中的ID 值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-18
        • 2018-08-21
        • 1970-01-01
        • 2015-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-03
        相关资源
        最近更新 更多