Dmy*_*kov 36 java compilation maven
我只是想在编译时在我的Java类中使用maven占位符以减少重复.
像这样的东西:
的pom.xml
<properties>
<some.version>1.0</some.version>
</properties>
Run Code Online (Sandbox Code Playgroud)
SomeVersion.java
package some.company;
public class SomeVersion {
public static String getVersion() {
return "${some.version}"
}
}
Run Code Online (Sandbox Code Playgroud)
And*_*sov 58
只需使用这样的内容在src/main/resources中创建文件app.properties
application.version=${project.version}
Run Code Online (Sandbox Code Playgroud)
然后像这样启用maven过滤
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
Run Code Online (Sandbox Code Playgroud)
这就是全部 - 在应用程序代码中只读取属性文件
ClassPathResource resource = new ClassPathResource( "app.properties" );
p = new Properties();
InputStream inputStream = null;
try {
inputStream = resource.getInputStream();
p.load( inputStream );
} catch ( IOException e ) {
LOGGER.error( e.getMessage(), e );
} finally {
Closeables.closeQuietly( inputStream );
}
Run Code Online (Sandbox Code Playgroud)
并提供这样的方法
public static String projectVersion() {
return p.getProperty( "application.version" );
}
Run Code Online (Sandbox Code Playgroud)
Jer*_*oen 10
即使它不是一个非常好的解决方案,也可以使用默认的maven资源插件.
首先,您需要指定资源插件.
<project>
<build>
<!-- Configure the source files as resources to be filtered
into a custom target directory -->
<resources>
<resource>
<directory>src/main/java</directory>
<filtering>true</filtering>
<targetPath>../filtered-sources/java</targetPath>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
Run Code Online (Sandbox Code Playgroud)
之后,您将需要更改编译器插件的"默认"配置.
<project>
<build>
<!-- Overrule the default pom source directory to match
our generated sources so the compiler will pick them up -->
<sourceDirectory>target/filtered-sources/java</sourceDirectory>
</build>
</project>
Run Code Online (Sandbox Code Playgroud)
我所知道的最简单的方法是使用Templating Maven Plugin。
将插件声明添加到您的 pom:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>templating-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<id>filter-src</id>
<goals>
<goal>filter-sources</goal><!-- add this if you filter main sources -->
<goal>filter-test-sources</goal><!-- add this if you filter test sources -->
</goals>
</execution>
</executions>
</plugin>
Run Code Online (Sandbox Code Playgroud)
如果您要过滤主要来源:
src/main/java-templates src/main.如果您也在过滤测试来源:
src/test/java-templates src/test.假设您的来源包含有效的占位符,例如:
package some.company;
public class SomeVersion {
public static String getVersion() {
return "${project.version}"
}
}
Run Code Online (Sandbox Code Playgroud)
现在,当您compile或test您的项目时,这些占位符应该已经受到重视。
希望能帮助到你。
| 归档时间: |
|
| 查看次数: |
33213 次 |
| 最近记录: |