将Maven参数注入Java类

pet*_*udo 3 java code-injection maven

我想将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>
Run Code Online (Sandbox Code Playgroud)

在班上

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

@Parameter(defaultValue = "test.password", readonly = true)
private String userPassword;
Run Code Online (Sandbox Code Playgroud)

she*_*lic 7

我会maven-resources-plugin用来生成一个.properties文件,避免生成代码.

<build>
  <resources>
    <resource>
      <directory>src/main/resources</directory>
      <filtering>true</filtering>
    </resource>
  </resources>
<build>
Run Code Online (Sandbox Code Playgroud)

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

testMail = ${test.email}
propertyName = ${maven.variable.name}
Run Code Online (Sandbox Code Playgroud)

在Java中访问它:

getClass().getResourceAsStream("/com/example/your/file.properties")
Run Code Online (Sandbox Code Playgroud)

为了更进一步,您可以通过以下方式强制执行该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>
Run Code Online (Sandbox Code Playgroud)