static类型autowired 注入失败

本文探讨了在Spring框架中,尝试将commonService对象注入到静态变量时遇到的NullPointerException异常原因。由于静态变量不属于对象层面,Spring无法进行依赖注入。文章提供了一种解决方案,通过@PostConstruct注解初始化静态成员变量,实现依赖注入。

原代码:注入commonService对象失败

  @Autowired
    private static CommonService commonService;

  public static List<Map<String, Object>> getCode(String codeType, boolean allOption ,String orderType){ return commonUtil.commonService.getCode(codeType, allOption, orderType); }
commonService在static状态下不能够被依赖注入,会抛出运行时异常java.lang.NullPointerException,为什么呢?
静态变量/类变量不是对象的属性,而是一个类的属性,spring则是基于对象层面上的依赖注入. 

解决方式1:

  @Autowired
    private CommonService commonService;
    private static CommonUtil commonUtil;
    
    @PostConstruct
    public void init() {
        commonUtil = this;
        commonUtil.commonService = this.commonService;
    }
    
    public static List<Map<String, Object>> getCode(String codeType,  boolean allOption ,String orderType){
        return commonUtil.commonService.getCode(codeType, allOption, orderType);
    }

 

转载于:https://www.cnblogs.com/zhouyeqin/p/8150594.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值