1. 概要

この短いチュートリアルでは、JavaアプリケーションからMavenのpom.xml内で定義された変数を使用する方法を見ていきます。

2. プラグインの構成

この例では、Mavenプロパティプラグインを使用します。

このプラグインはgenerate-resourcesフェーズにバインドし、コンパイル中にpom.xmlで定義された変数を含むファイルを作成します。 次に、実行時にそのファイルを読み取って値を取得できます。

プロジェクトにプラグインを含めることから始めましょう。

<plugin>
    <groupId>org.codehaus.mojo</groupId> 
    <artifactId>properties-maven-plugin</artifactId> 
    <version>1.0.0</version> 
    <executions> 
        <execution> 
            <phase>generate-resources</phase> 
            <goals> 
                <goal>write-project-properties</goal> 
            </goals> 
            <configuration> 
                <outputFile>${project.build.outputDirectory}/properties-from-pom.properties</outputFile> 
            </configuration> 
        </execution> 
    </executions> 
</plugin>

次に、変数に値を指定します。さらに、pom.xml内で定義しているため、Mavenプレースホルダーも使用できます。

<properties> 
    <name>${project.name}</name> 
    <my.awesome.property>property-from-pom</my.awesome.property> 
</properties>

3. プロパティの読み取り

次に、構成からプロパティにアクセスします。 クラスパス上のファイルからプロパティを読み取るための簡単なユーティリティクラスを作成しましょう。

public class PropertiesReader {
    private Properties properties;

    public PropertiesReader(String propertyFileName) throws IOException {
        InputStream is = getClass().getClassLoader()
            .getResourceAsStream(propertyFileName);
        this.properties = new Properties();
        this.properties.load(is);
    }

    public String getProperty(String propertyName) {
        return this.properties.getProperty(propertyName);
    }
}

次に、値を読み取る小さなテストケースを作成します。

PropertiesReader reader = new PropertiesReader("properties-from-pom.properties"); 
String property = reader.getProperty("my.awesome.property");
Assert.assertEquals("property-from-pom", property);

4. 結論

この記事では、Mavenプロパティプラグインを使用してpom.xmlで定義された値を読み取るプロセスを実行しました。

いつものように、すべてのコードはGitHub利用できます。