peter_budo
peter_budo

Reputation: 1748

Inject Maven parameter into Java class

I would like to inject settings.xml profile parameters into Java class. I tried to use maven-annotation-plugin but values came as null. I wonder if this is because this plugin is designed for Mojo

Setting.xml snippet

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

In class

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

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

Upvotes: 3

Views: 3226

Answers (2)

shellholic
shellholic

Reputation: 6114

I would use maven-resources-plugin to generate a .properties file and avoid generating code.

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

And create the file src/main/resources/com/example/your/file.properties:

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

In Java access it with:

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

To go further, you can enforce the presence of the test.email property with 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>

Upvotes: 7

Jasper de Vries
Jasper de Vries

Reputation: 20243

You could use Maven to generate a Properties file and load it in your Java Class.

Upvotes: 1

Related Questions