Spring中@Autowired注入请求作用域Bean为空触发NPE问题求解
问题根因分析
- 核心原因是你手动实例化了Spring管理的Bean:你在
AssetDetailsImpl的function2中通过new AssetUtil()创建的对象完全脱离Spring容器管控,Spring不会为手动创建的对象处理@Autowired、@Inject这类依赖注入注解,所以AssetUtil中的AssetDetailsImpl自然为null,这也是你移除request scope注解后问题依旧存在的原因,和作用域配置没有直接关联。 - 额外的语法问题:你提供的
AssetUtil中test1方法定义缺失括号,正确写法应为public void test1(),请先修正语法错误再做后续排查。 - 若保留
request scope配置的潜在问题:AssetUtil是默认单例Bean,直接注入request作用域的Bean会导致生命周期不匹配,即使修正实例化问题也会出现启动异常或调用异常,需要补充代理配置。
解决方案
第一步:修正实例化逻辑,不要手动new Spring托管Bean
调整AssetDetailsImpl的代码,改为注入AssetUtil而非手动创建:
package com.assets; @Component // 保留request scope需要加proxyMode,移除scope的话可删除下一行 @Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS) public class AssetDetailsImpl implements AssetApi { // 注入Spring管理的AssetUtil实例 @Autowired private AssetUtil assetUtil; public void function1(){ .... } public void function2(){ // 直接用注入的实例,不要new assetUtil.test1(); } }
第二步:(可选,保留request scope时需要配置)调整作用域的代理模式
给AssetDetailsImpl的@Scope注解补充代理模式配置,让Spring注入代理对象,解决单例Bean注入请求作用域Bean的生命周期不匹配问题:
// 需要导入对应的类 import org.springframework.web.context.WebApplicationContext; import org.springframework.context.annotation.ScopedProxyMode; @Component @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) public class AssetDetailsImpl implements AssetApi { // 原有代码 }
第三步:检查组件扫描配置
确保你的Spring启动类或配置类的@ComponentScan注解包含了com.assets包,保证两个类的@Component注解能被Spring识别并托管到容器中。
内容的提问来源于stack exchange,提问作者Tech Geek
相关产品推荐
相关产品推荐

