将Maven参数注入Java类

时间:2013-03-18 11:14:04

标签: java maven code-injection

我想将settings.xml配置文件参数注入Java类。我尝试使用maven-annotation-plugin,但值为null。我想知道这是不是因为这个插件是为Mojo设计的

Setting.xml片段

  <profiles>
    <profile>
      <id>APP_NAME</id>
      <properties>
        <test.email>USER_EMAIL</test.email>
        <test.password>USER_PASSWORD</test.password>
      </properties>
    </profile>
  </profiles>

在课堂上

@Parameter(defaultValue = "test.email", readonly = true)
private String userEmail;

@Parameter(defaultValue = "test.password", readonly = true)
private String userPassword;

2 个答案:

答案 0 :(得分:7)

我会使用maven-resources-plugin生成.properties文件并避免生成代码。

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

并创建文件src/main/resources/com/example/your/file.properties

testMail = ${test.email}
propertyName = ${maven.variable.name}

在Java中访问它:

getClass().getResourceAsStream("/com/example/your/file.properties")

为了更进一步,您可以使用test.email强制maven-enforcer-plugin属性存在:

<build>
  <plugin>
    <artifactId>maven-enforcer-plugin</artifactId>
    <executions>
      <execution>
        <id>enforce-email-properties</id>
        <goals>
          <goal>enforce</goal>
        </goals>
        <configuration>
          <rules>
            <requireProperty>
              <property>test.email</property>
              <message>
                The 'test.email' property is missing.
                It must [your free error text here]
              </message>
            </requireProperty>
          </rules>
        </configuration>
      </execution>
    </executions>
  </plugin>
</build>

答案 1 :(得分:1)

您可以使用Maven在Java类中生成Properties文件和load文件。

相关问题