如何从Spring Boot War应用程序访问gradle.properties文件值?

时间:2016-07-14 15:05:55

标签: java gradle spring-boot

我想从Spring Boot应用程序的根目录中的gradle.properties文件中访问一个值。 (要在主页上显示项目的版本。)

我正在构建一场战争,将我的Spring Boot应用程序部署到服务器,并使用外部application.properties文件(#9 on this list),因此this solution对我不起作用。

我尝试this solution,但是我把gradle.properties文件放在战争中的任何地方(我已经尝试了该目录结构中的每个可能的位置),我无法使用this method访问它。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

这是在上面指定的限制范围内为我工作的结果:

一句话摘要

为了在我的部署管道(gradle build - > war - >嵌入式tomcat)和开发(IntelliJ)中工作,我需要一个虚拟属性文件进行开发并在实际属性文件中复制gradle build。

<强>代码

./ gradle.properties

version=x.x.x

./的src /主/资源/ my-project.properties

version=development

./的build.gradle

war {
    rootSpec.exclude("**/my-project.properties")
    from('.') {
        include 'gradle.properties'
        into('WEB-INF/classes')
        rename('gradle.properties', 'my-project.properties')
    }   
}

./ SRC /主/ JAVA / COM /公司/版本/ VersionComponent.java

private String getVersion() {
    String propertyVersion = "";
    Properties properties = new Properties();
    InputStream input = null;
    try {
        input = VersionComponent.class.getClassLoader().getResourceAsStream("my-project.properties");
        properties.load(input);
        propertyVersion = properties.getProperty("version");
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return propertyVersion;
}

答案 1 :(得分:1)

我正在使用grails工作,这也是在spring boot上构建的。和你一样,我想从我的gradle文件中传递属性,但对我来说,它来自build.gradle并且在junit执行期间使用。

注意:有关加载application.properties的方法列表,而不是gradle.properties,您可以查看here。只是为了确保我们在同一页面上,如果您正在尝试对正在使用的应用程序进行版本化(可能将其显示给某个用户),您应该在application.properties中设置它而不是gradle.properties。如果你想要后者,你need to replace the properties in the file you plan on using with gradle,并更改值,这是更复杂的。

无论如何,我采用的一种方法是让我在测试执行期间从build.gradle中注入属性。

test {
    def defaultLoginUrl = System.getProperty("testing.defaults.loginUrl")

    systemProperty "testing.defaults.loginUrl", defaultLoginUrl?: "https://localhost:8443/"
}

在我的Java代码中:

public String getLoginUrl() {
    return System.getProperty("testing.defaults.loginUrl")
}

最后,如果您想要access the file as an input stream,则应将其放在the resources directory, and use the context to fetch it中。但是,在我看来,application.properties是通过阅读你的帖子,正是你想要的。在you quoted问题中类似地解决了这个概念,因为当您准备部署它时,从构建文件加载属性不常见。