Spring Boot自动扩展属性

1.概述

在本文中,我们将探讨Spring通过Maven和Gradle构建方法提供的属性扩展机制。

2. Maven

2.1.默认配置

对于使用spring-boot-starter-parent的 Maven项目,不需要额外的配置来使用属性扩展:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.4.RELEASE</version>
</parent>
 

现在我们可以使用@ ... @占位符扩展项目的属性以下是我们如何将项目从Maven中获取的版本保存到我们的属性中的示例:

expanded.project.version=@project.version@
expanded.project.property=@custom.property@
 

我们只能在匹配这些模式的配置文件中使用这些扩展:

  • ** /application* .yml
  • ** /application* .yaml
  • ** /application* .properties

2.2.手动配置

如果没有spring-boot-starter-parent parent,我们需要手动配置这个过滤和扩展。我们需要在我们的pom.xml文件的< build>部分中包含resources元素

<resources>
    <resource>
        <directory>${basedir}/src/main/resources</directory>
        <filtering>true</filtering>
        <includes>
            <include>**/application*.yml</include>
            <include>**/application*.yaml</include>
            <include>**/application*.properties</include>
         </includes>
    </resource>
</resources>   
 

并在< plugins>中

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <version>2.7</version>
    <configuration>
        <delimiters>
            <delimiter>@</delimiter>
        </delimiters>
        <useDefaultDelimiters>false</useDefaultDelimiters>
    </configuration>
</plugin>
 

如果需要使用${variable.name}类型的标准占位符,我们需要将useDefaultDelimeters设置true,并且您的application.properties将如下所示:

expanded.project.version=${project.version}
expanded.project.property=${custom.property}

3.结论

在本快速教程中,我们了解了如何使用Maven构建方法自动扩展Spring Boot属性。

原文地址:https://www.cnblogs.com/gc65/p/10618443.html