Spring Boot以CommandLineJobRunner启动时无法加载profile配置文件问题
问题根因
你当前配置加载失败的核心原因是Spring Boot的配置加载逻辑没有被触发,对应配置错误和解决方案如下:
1. 修正启动主类配置
你在build.gradle中指定的主类是Spring Batch原生的CommandLineJobRunner,该启动器不会初始化Spring Boot上下文,自然不会加载Spring Boot的配置文件、profile规则和属性绑定逻辑。
解决方案
- 新增Spring Boot主启动类:
package com.wego.gradlejedisexample; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.ConfigurationPropertiesScan; import org.springframework.boot.context.properties.EnableConfigurationProperties; @SpringBootApplication @EnableConfigurationProperties(AppConfig.class) @ConfigurationPropertiesScan public class BatchApplication { public static void main(String[] args) { SpringApplication.run(BatchApplication.class, args); } }
- 修改
build.gradle的bootJar配置:
bootJar { mainClassName = 'com.wego.gradlejedisexample.BatchApplication' }
2. 修正配置属性类注解
AppConfig类不需要加@Configuration注解,该注解会将它识别为普通配置类,影响属性绑定优先级,直接保留@ConfigurationProperties即可:
@ConfigurationProperties("config") @Data public class AppConfig { private RedisConfig redis; @Data public static class RedisConfig { private String host; private int port; } }
3. 简化启动命令
Spring Boot默认会自动加载激活profile对应的application-{profile}.yml配置文件,不需要额外指定spring.config.additional-location参数,修改后的启动命令如下:
java -Dspring.profiles.active=batch -jar build/libs/GradleJedisExample-0.0.1-SNAPSHOT.jar --message=hi
如果需要关闭Spring Boot自动执行Job的逻辑,可以在application-batch.yml中添加配置:
spring: batch: job: enabled: false
自行通过CommandLineRunner手动触发Job执行即可。
内容的提问来源于stack exchange,提问作者Amjad Aziz
相关产品推荐
相关产品推荐

