Spring Boot项目中,如何在yml配置文件中读取maven pom.xml文件中的properties标签下的属性值

发布于:2024-06-06 ⋅ 阅读:(134) ⋅ 点赞:(0)

一、前言

在最近的项目开发过程中,有一个需求,需要在Spring Boot项目的yml配置文件中读取到mave的 pom.xml文件中的properties标签下的属性值,这个要怎么实现呢?

二、技术实践

  1. pom.xml文件中增加测试属性

    <properties>
        <test.maven.pro>I am test pro.</test.maven.pro>
    </properties>
    
  2. 在yml配置文件中,使用@...@方式获取

maven:
  test:
    pro: @test.maven.pro@
  1. 测试属性读取
@SpringBootApplication
public class Main {
    
    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(Main.class, args);
        
        System.out.println("maven.test.pro=" + run.getEnvironment().getProperty("maven.test.pro"));
    }

}
  1. 启动项目测试
20:13:59.064 [main] ERROR org.springframework.boot.SpringApplication - Application run failed
org.yaml.snakeyaml.scanner.ScannerException: while scanning for the next token
found character '@' that cannot start any token. (Do not use @ for indentation)
 in 'reader', line 82, column 10:
        pro: @test.maven.pro@
             ^

    at org.yaml.snakeyaml.scanner.ScannerImpl.fetchMoreTokens(ScannerImpl.java:445)
    at org.yaml.snakeyaml.scanner.ScannerImpl.checkToken(ScannerImpl.java:238)

运行项目时,可以看到,直接报错了,面对这个错误要怎么解决呢?

3. 问题解决

  1. 在pom.xml中新增如下配置:

    <build>
            <resources>
                <resource>
                    <directory>src/main/resources</directory>
                    <filtering>true</filtering>
                </resource>
            </resources>
        </build>
    
  2. 重新运行测试

在这里插入图片描述

可以看到,此时可以正常读取pom.xml文件中的属性了。