静态注入示例

在一些工具类中可能会依赖 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 初始化了工具类对象,使对象注入可以进行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值