Spring Boot @Value注入配置为null求助:指定扫描包类读取失败
Spring Boot配置读取为null问题排查
问题现象
开发Spring Boot应用时,com.binance.bot.timeandsales包下新增的类无法读取application.properties中的配置,字段始终为null,但其他包内的类可正常读取配置,且该包已在@SpringBootApplication的扫描路径中指定。
相关代码片段
启动类代码
@SpringBootApplication(scanBasePackages = {"com.binance.bot.timeandsales", <some other packages>}) @Configuration @EnableScheduling public class BinanceTimeAndSalesApplication implements CommandLineRunner { @Autowired AggTradeEventSubscriptionListener aggTradeEventSubscriptionListener; }
同一文件中的内部Bean类
@Component class AggTradeEventSubscriptionListener implements SubscriptionListener<AggregateTradeEvent> { @Value("${binance.api}") private String apiUrl; }
application.properties配置
binance.api=https://fapi.binance.com
pom.xml配置
<properties> <start-class>com.binance.bot.timeandsales.BinanceTimeAndSalesApplication</start-class> </properties>
问题根源
核心问题是内部类的访问权限限制导致Spring无法正确处理组件扫描与依赖注入:
AggTradeEventSubscriptionListener是BinanceTimeAndSalesApplication的默认包访问权限内部类,Spring的组件扫描机制无法识别并实例化非公开的内部类。- 即使添加了
@Component注解,由于访问权限限制,Spring无法通过反射创建该类实例,自然无法完成@Value的配置注入,最终导致apiUrl为null。
解决方案
有两种可行的修复方式:
修改内部类访问修饰符为public
将AggTradeEventSubscriptionListener改为公开类,确保Spring能正常扫描并实例化:@Component public class AggTradeEventSubscriptionListener implements SubscriptionListener<AggregateTradeEvent> { @Value("${binance.api}") private String apiUrl; }将内部类提取为独立顶层类
把AggTradeEventSubscriptionListener从启动类文件中移出,作为com.binance.bot.timeandsales包下的独立类,保持默认或public访问权限即可,Spring会自动完成扫描与注入。
补充验证点
- 移除
application.properties中配置项的前置空格,避免键名识别错误:binance.api=https://fapi.binance.com - 确认
@SpringBootApplication的scanBasePackages中com.binance.bot.timeandsales的拼写无错误。
内容的提问来源于stack exchange,提问作者Kannan J
相关产品推荐
相关产品推荐

