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

一、前言

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

二、技术实践

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

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

yml 复制代码
maven:
  test:
    pro: @test.maven.pro@
  1. 测试属性读取
java 复制代码
@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. 启动项目测试
powershell 复制代码
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中新增如下配置:

    xml 复制代码
    <build>
            <resources>
                <resource>
                    <directory>src/main/resources</directory>
                    <filtering>true</filtering>
                </resource>
            </resources>
        </build>
  2. 重新运行测试

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

相关推荐
JustNow_Man12 分钟前
【Claude Code】 中给 Python + XML 项目建立可靠验证体系
xml·linux·python
砍材农夫39 分钟前
redis|spring-boot redis geo|附近定位功能
java·spring boot·redis
智码看视界1 小时前
Day18 SpringBoot自动配置原理:从@SpringBootApplication开始
java·spring boot·后端·自动装配
沫离痕18 小时前
Cassandra 4.0.11 Docker 安装与配置手册
java·spring boot
山东点狮信息科技有限公司18 小时前
SpringBoot+VUE3,一套系统完成OA+HRM+CRM+MES+合同+项目管理 —— 深度解析点狮全业务管理平台
java·spring boot·后端
卓怡学长20 小时前
w263基于springboot + vue 健康饮食管理系统
java·数据库·vue.js·spring boot·spring·intellij-idea
万亿少女的梦16821 小时前
基于Spring Boot、Vue.js和MySQL的超市管理系统设计与实现
java·vue.js·spring boot·mysql·管理系统
AI产品实战1 天前
Gradle打包生成dependencies.xml详解
xml·java·gradle