java - 我可以将来自 Maven 的属性(在 settings.xml 中定义的密码)注入(i

我通过我在 ~/.m2/settings.xml 中为我的部署插件定义的属性定义服务器密码(不过,可以在任何地方,包括 pom.xml)。我想为我的集成测试使用相同的属性。有办法吗?

如果没有,有没有一种方便的方法可以在 Maven 和 TestNG 之间共享属性?

我想编写一个很好的测试套件,它可以在不同的持续集成服务器上运行,指向不同的远程主机(开发、测试、登台和生产),而无需修改代码。

我在 settings.xml 中定义远程服务的凭据:

<properties>
<my.host>http://my.company.com</my.host>
<my.username>my-un</my.username>
<my.password>my-pw</my.password>
</properties>

我希望能够使用以下方法在我的单元/集成测试 (src/test/resources) 中引用属性:

<?xml version="1.0" encoding="UTF-8"?>
<beans....
    <bean class="java.lang.String" id="un">
        <constructor-arg value="${my.username}"/>
    </bean>
    <bean class="java.lang.String" id="pw">
        <constructor-arg value="${my.password}"/>
    </bean>
</beans>

有什么选择吗?有没有其他人尝试过这个?我正在编写很多需要在我的测试中授权的 REST 测试。

谢谢!

最佳答案

当然。 Maven resource filtering是要走的路。

这是一个示例配置(匹配 *-context.xml 的文件将被过滤,其他文件不会):

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
            <includes>
                <include>**/*-context.xml</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>false</filtering>
            <excludes>
                <exclude>**/*-context.xml</exclude>
            </excludes>
        </resource>
    </resources>
</build>

另一种方法是使用 Properties Maven Plugin至write all project properties to a file并使用 the PropertyPlaceholderConfigurer mechanism 从 Spring 中引用该文件.

Maven 配置:

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>properties-maven-plugin</artifactId>
            <version>1.0-alpha-2</version>
            <executions>
                <execution>
                    <phase>generate-test-resources</phase>
                    <goals>
                        <goal>write-project-properties</goal>
                    </goals>
                    <configuration>
                        <outputFile>${project.build.testOutputDirectory}/mavenproject.properties</outputFile>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

Spring 配置:

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

关于java - 我可以将来自 Maven 的属性(在 settings.xml 中定义的密码)注入(inject)到我的 Spring 容器中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4107222/

相关文章:

spring - 创建 ServletContext 资源中定义的名称为 'org.springfr

java - Spring/Hibernate 测试 : Inserting test data a

java - 从 4.2.0.RC3 升级到 4.2.0.RELEASE 时出现 Spring As

spring - 如果我忘记将 Spring SessionStatus 标记为 "Complete

java - Spring根应用上下文和servlet上下文混淆

spring - Java EE 和 Spring 框架的区别

spring - 如何在 Spring Boot 中为文件上传指定临时目录?

java - Spring Security Configuration @Order 不是唯一异常

java - @Transactional(propagation=Propagation.REQU

java - 处理一个 Spring bean/接口(interface)的多个实现