java - 将 settings.xml 中设置的属性访问到 spring.xml

标签 java spring maven properties-file

我在 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是

Exception in thread "main" org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: class path resource [src/main/resources/test.properties] cannot be opened because it does not exist

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

最佳答案

您错误配置了属性占位符。 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 配置文件,然后将其作为属性占位符注入(inject)到您的 spring.xml 中:

测试.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> 

关于java - 将 settings.xml 中设置的属性访问到 spring.xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22109869/

相关文章:

java - 多次从 Kafka 读取同一条消息

java - 如何实现 isWeekday() 和 isWeekend()?

java - 为什么我在这里收到 InvalidUseOfMatchersException?

java - 为什么带有 catch Exception 的空 try block 会编译?

maven - 如果 child 的 pom 版本与 parent 的聚合器 pom 及其子模块的版本不同,请避免错误的版本插值

maven - 在 Jenkins(测试)实例中禁用 Maven 部署后构建操作?

安卓人工集成

java - 从 fragment 中检索上下文

java - 如何使用 REST Web 服务和 Spring 中的 CompletableFuture 类捕获异常?

java - Spring - 依赖注入(inject) - 哪个优先?