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

一、前言

在最近的项目开发过程中,有一个需求,需要在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文件中的属性了。

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值