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文件中的属性了。

相关推荐
早安试言16 分钟前
maven安装
java·maven
攻城有术1 小时前
专项攻克-SpringBoot启动后 Bean的实例数量问题
java·spring boot·后端
程序员贺加贝2 小时前
别把 ThreadLocal 写进 Serializer:一次 SaaS 多租户 Jackson 上下文污染排查
java·spring boot
evans在进步2 小时前
Spring Boot 工程化核心详解:Parent、Starter、热部署、事务与多数据源
spring boot·后端·python
卓怡学长2 小时前
w181springboot机场乘客服务系统
java·数据库·spring boot·spring·intellij-idea
罗超驿3 小时前
SpringBoot 快速入门
java·spring boot·后端
Java内核笔记5 小时前
Spring Boot 4 虚拟线程源码剖析:Tomcat 线程池是怎么被换掉的
spring boot·后端
Y001112365 小时前
springboot+vue项目实战
vue.js·spring boot·后端
FYKJ_20106 小时前
django学习成绩预警系统10905
java·javascript·spring boot·python·spark·django·php
卓怡学长7 小时前
w192基于springboot教务管理系统
java·数据库·spring boot·spring·maven·intellij-idea