在springboot的默认配置文件application.properties中引用pom.xml中的变量

在application.properties中我们引用了hostname这个变量,其中@hostname@代表的是pom.xml中的一个变量

server.port=8081

eureka.instance.hostname=127.0.0.1
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.service-url.defaultZone=http://@hostname@:${server.port}/eureka/

在pom.xml中

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-clound.version>Greenwich.SR1</spring-clound.version>
        <eureka-server.version>2.1.1.RELEASE</eureka-server.version>
        <spring-boot.version>2.1.3.RELEASE</spring-boot.version>
        <hostname>127.0.0.1</hostname>
    </properties>

其中hostname就是我们在application.properties中引用的变量。
在这里插入图片描述
按照上述方式就可以访问在pom.xml中变量了。。

另外说明的是:

由于${ }这种方式会被maven处理。如果你pom继承了spring-boot-starter-parent,Spring Boot已经将maven-resources-plugins默认的 ${}方式改为了@@方式,如@name@,而你要用的是 ${变量名}这种方式来获取变量。

所以如何解决这种情况呢?

先说明下这种情况的使用方式:

比如我的application.properties如下:

server.port=8081

eureka.instance.hostname=127.0.0.1
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.service-url.defaultZone=http://${hostname}:${server.port}/eureka/

注意其中原来的@hostname@我已经改成了${hostname}这种方式。

如果项目不能运行,那么需要重新mvn -clean然后再mvn -compile。

如果按照上面这种方式如何获取呢?
那么在pom.xml文件添加一个插件(plugin),原来的变量声明还是不变:如下

<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-resources-plugin</artifactId>
   <configuration>
       <encoding>UTF-8</encoding>
       <useDefaultDelimiters>true</useDefaultDelimiters>
   </configuration>
</plugin>

如果按照上面这种配置之后,那么在application.properties中使用${变量名}和@变量名@这两种方式都可以获取到。。。

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐