Access maven project version in Spring config files

狂风中的少年 提交于 2019-11-28 09:29:40

You can use Maven filtering as already suggested.

Or you could just read the pom.properties file created by Maven under META-INF directory directly with Spring:

<util:properties id="pom" 
     location="classpath:META-INF/groupId/artifactId/pom.properties" />

and use the bean.

The only drawback of the later approach is that the pom.properties is created at package phase time (and won't be there during, say, test).

drekka

One technique would be to use mavens filtering. You can insert placeholders in resource files like which then get replaced with values from the build during the resource phase.

Look up "How do I filter resource files?" in the Maven getting started guide

tzolov

Use the @PropertySource annotation to add the pom.properties file created by Maven in the META-INF directory. Note that the file doesn't exist until the package phase. To avoid errors during testing set the ignoreResourceNotFound=true and add a default value on the property being read (e.g. none below). 

@Service
@PropertySource(value = "classpath:META-INF/maven/io.pivotal.poc.tzolov/hawq-rest-server/pom.properties", ignoreResourceNotFound=true)
public class MyClass {
    private String applicationPomVersion;

    @Autowired
    public MyClass(@Value("${version:none}") String applicationVersion ) {
        this.applicationPomVersion = applicationVersion;
    }

    public String getApplicationPomVersion() {
        return this.applicationPomVersion;
    }
}

We deploy property files outside of the web app. The files can then be filtered at deployment time.

If using Jetty one can put the file under $JETTY_HOME/resources or use the extraClassPath feature to load the property file at runtime.

Carlos

I think the right way of gather application version is the one explained in this thread: https://stackoverflow.com/a/2713013/840635 through getClass().getPackage().getImplementationVersion().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!