首页 > 其他 > 详细

static类型autowired 注入失败

时间:2017-12-30 18:47:46      阅读:249      评论:0      收藏:0      [点我收藏+]

原代码:注入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);
    }

 

static类型autowired 注入失败

原文:https://www.cnblogs.com/zhouyeqin/p/8150594.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!