在一些工具类中可能会依赖 service 层的对象,一般情况下工具类都是使用静态方法,对应的成员变量也需要声明为静态的,此时如果直接使用 @Autowired 进行依赖注入,在方法调用的时候会报 NullpointerException.废话不多说先上代码
@Component
public class TenderMakeTagUtil {
@Autowired
private static AttrSpecService attrSpecService;
@Autowired
private static CorpusKeywordUtil corpusKeywordUtil;
@Autowired
private static TenderCorpusKeywordMapper tenderCorpusKeywordMapper;
@Autowired
private static TenderDataAttachPyMapper tenderDataAttachPyMapper;
@Autowired // 静态注入代码
public TenderMakeTagUtil(AttrSpecService attrSpecService, CorpusKeywordUtil corpusKeywordUtil,
TenderCorpusKeywordMapper tenderCorpusKeywordMapper, TenderDataAttachPyMapper tenderDataAttachPyMapper) {
this.attrSpecService = attrSpecService;
this.corpusKeywordUtil = corpusKeywordUtil;
this.tenderCorpusKeywordMapper = tenderCorpusKeywordMapper;
this.tenderDataAttachPyMapper = tenderDataAttachPyMapper;
}
public static TenderMakeTagUtil tenderMakeTagUtil;
@PostConstruct // 静态注入代码
public void init() {
tenderMakeTagUtil = this;
}
public static TenderDataPy tenderDataMarkTag(TenderDataPy tenderDataPy) {
// 代码省略
return tenderDataPy;
}
public static void marketProjectType(TenderDataPy record, String tenderOrganization) {
// 代码省略
return result;
}
}
分析
1 如果没有那两段静态注入代码,我们会发现运行该工具类时会报java.lang.NullPointerException。因为静态方法是属于类的,而普通方法则属于对象,spring注入只在容器中实例化变量的,并且静态是优先于对象存在的,所以直接在静态方法中调用注入的静态变量其实是null的
2 @PostConstruct 初始化了工具类对象,使对象注入可以进行