maven property에 접근하는 방법

 

https://www.baeldung.com/java-accessing-maven-properties (해당 글을 구글 번역 돌리고 작성자가 약간의 교정) 

1. 개요

이 짧은 튜토리얼에서는 Java 애플리케이션에서 Maven의 pom.xml 내에 정의된 변수를 사용하는 방법을 살펴보겠습니다.

 

2. 플러그인 구성

이 예제에서는 Maven Properties Plugin을 사용합니다. (https://www.mojohaus.org/properties-maven-plugin/)
이 플러그인은 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  placeholder를 사용할 수도 있습니다. Maven placeholder: https://github.com/cko/predefined_maven_properties/blob/master/README.md

 

predefined_maven_properties/README.md at master · cko/predefined_maven_properties

Contribute to cko/predefined_maven_properties development by creating an account on GitHub.

github.com

<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);
    }
}

다음으로 위에 작성한 속성을 읽는 테스트 케이스를 작성합니다. 

// 플러그인을 포함시켰을때 <outputFile>하위에 설정한 파일이름
PropertiesReader reader = new PropertiesReader("properties-from-pom.properties"); 
// <properties> 태그 안에 설정한 <my.awesome.property>값을 읽는다.
String property = reader.getProperty("my.awesome.property"); 
// <my.awesome.property> 값이 property-from-pom 이었는데 해당 값과 동일한지 테스트한다.
Assert.assertEquals("property-from-pom", property);

 

4. 결론

이번 글에서는 Maven Properties Plugin을 이용하여 pom.xml에 정의된 값을 읽는 과정을 살펴보았습니다.
언제나 그렇듯이 모든 코드는 GitHub에서 사용할 수 있습니다.

'정보 > Server' 카테고리의 다른 글

[Project] The settings.xml File in Maven  (1) 2024.04.26
[Project] Maven Packaging Types  (0) 2024.04.26
[Project] Maven Properties Defaults  (1) 2024.04.25
[WSL] WSL 환경에 Python 개발환경설정  (0) 2024.04.04
[Windows] WSL 세팅  (0) 2024.04.04

+ Recent posts