static类型autowired 注入失败
原代码:注入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); }