IntelliJ中application.yml读取Maven变量抛ScannerException但构建正常求助
在application.yml中配置info:app:parent: @project.parent.version@时抛出ScannerException异常,但配置info:app:version: @java.version@无问题;使用info:app:parent: @parent@正常,info:app:parent: @parent.version@则触发异常。
异常信息:
11:28:01.627 [restartedMain] 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 17, column 13: parent: @project.parent.version@ ^
补充背景:
使用mvn package -DskipTests构建后,通过mvn spring-boot:run -D"spring-boot.run.profiles"=prod -D"spring-boot.run.arguments"="<args>"运行,访问actuator的info端点可正常获取父版本。尝试过重新加载pom.xml、mvn clean、清除IntelliJ缓存并重启均无效。环境为Java 21 + Spring Boot Parent 3.1.4,降级到Java 17 + Spring Boot Parent 3.1.3也未解决问题。
1. 确保Maven资源过滤配置正确
在pom.xml的build节点中添加资源过滤配置,让Maven处理application.yml中的占位符:
<build> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> <includes> <include>application*.yml</include> </includes> </resource> </resources> <!-- 可选:指定maven-resources-plugin版本适配Spring Boot --> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>3.3.1</version> </plugin> </plugins> </build>
2. 让IntelliJ委托构建/运行行为给Maven
- 打开IntelliJ的
File → Settings,进入Build, Execution, Deployment → Build Tools → Maven → Runner - 勾选Delegate IDE build/run actions to Maven选项
- 应用设置后重启IDE
这样IDE运行项目时会调用Maven处理资源文件,自动替换@project.parent.version@这类占位符,避免SnakeYAML解析错误。
3. 确认YAML文件关联到Spring Boot配置编辑器
- 右键
application.yml文件,选择Open With → Spring Boot Config Editor - 或者在
Settings → Editor → File Types中,将application*.yml添加到Spring Boot Config Files的关联列表中
确保IDE识别该文件为Spring Boot配置文件,正确处理占位符逻辑。
4. 手动预处理资源后运行
如果不想委托给Maven,可先执行Maven命令生成处理后的资源文件:
mvn process-resources
该命令会把替换好占位符的application.yml生成到target/classes目录,然后在IntelliJ的运行配置中,设置资源路径指向target/classes,让IDE使用处理后的配置文件。
内容的提问来源于stack exchange,提问作者user22509994

