首页 文章

访问属性在settings.xml中设置为spring.xml

提问于
浏览
2

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

Setting.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 访问属性 .

2 回答

  • 0

    你错误配置了你的 property 占有者 . src / main / resource不在你的类路径中,你应该这样做:

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

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

    一个 . 直接过滤你的 Spring 天语境:

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

    湾或者过滤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>
    
  • 0

    我看到几点:

    • property-placeholder 的location属性是指类路径上的文件,但是你想在文件系统上使用一个文件,所以它必须是这样的:
    <context:property-placeholder location="file:///user_directory/.m2/settings.properties"/>
    
    • 您的设置文件是XML . 默认情况下,实际上是Java属性格式的文件 . 可能有使用自定义XML的方法,但我不熟悉 . 所以你的XML文件会转换成这样的东西:
    profile.id = default
    profile.activation.activateByDefault = true
    profile.properties.testName = Test
    ...
    
    • 稍后在 spring.xml 中引用您的属性时,只需使用 ${profile.id} 来放置 settings.properties 文件中的ID值 .

相关问题