java - 将 Maven 参数注入(inject) Java 类

标签 java maven code-injection

我想将 settings.xml 配置文件参数注入(inject) Java 类。我尝试使用 maven-annotation-plugin,但值为空。我想知道这是不是因为这个插件是为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;

最佳答案

我会使用 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")

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

<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>

关于java - 将 Maven 参数注入(inject) Java 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15475450/

相关文章:

java - Varargs Java 不明确调用

java - 如何在 Maven 项目(编译、构建、打包)中包含第 3 方 jar,其中添加本地 Maven 存储库不是一个选项?

c# 反射(或另一种通过注入(inject)的 dll 获取类值的方法)

java - 我想在 DoubleClick 事件上显示一些文本该怎么做?我已经附上了我的源代码

java - UI图布局

java - javax.servlet.ServletContext 和 javax.servlet.ServletException 类型无法解析

javascript - onClick 标签中的安全性如何防止 javascript 注入(inject)?

c++ - 为游戏制作地址查找器

java - 单击 anchor 时 HtmlUnit 没有任何反应

maven - 使用特定配置文件时禁用 Maven 插件