spring中Utils工具類注入問題


使用工具類的時候,我們想在static修飾的方法中,通過注入來調用其他方法,這里就存在問題。

  第一:普通工具類是不在spring的管理下,spring不會依賴注入

  第二:即便使用@Autowired完成注入,由於工具類是靜態方法,只能訪問靜態變量和方法。但是spring不能直接注入static的。

    如:

@Autowired
private static JcustomerMapper jcustomermapper;

  這樣直接注入會是null。為什么spring不能直接注入static變量

     static成員與類相關,其中static變量及初始化塊會在類加載器第一次加載類時初始化和執行。而spring管理的是對象實例的創建和屬性注入

    (初始化了static變量,也就是給該static變量分配內存了)

解決這兩個問題

  第一:在根據類上加入@Component,使它在spring的管理下,由spring完成該類的初始化和注入

  第二:  1.我們可以構建一個當前根據類對象的靜態變量 private static JcustomerUtils jcustomerutils;

       2.並且在初始化的時候把當前工具類對象賦值給這個變量   

@PostConstruct  //該注解的方法在構造函數執行后執行
 public void init() {
 jcustomerutils = this; 
} 

 

        3.此時我們注入其它對象

 @Autowired
    private  JcustomerMapper jcustomermapper;

        4.通過jcustomerutils.jcustomermapper就可以調用jcustomermapper的變量和方法了

 

 下面是具體的代碼

package com.jinsenianhua.user.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.jinsenianhua.common.utils.IDcardUtils;
import com.jinsenianhua.common.utils.MyPhoneUtils;
import com.jinsenianhua.common.utils.MyresultUtils;
import com.jinsenianhua.user.dao.JcustomerMapper;
import com.jinsenianhua.user.pojo.Jcustomer;
import com.jinsenianhua.user.pojo.JcustomerExample;
import com.jinsenianhua.user.pojo.JcustomerExample.Criteria;

@Component  //聲明組件 - 讓spring初始化的時候在spring上下文創建bean並完成注入
public class JcustomerUtils {
    
    @Autowired
    private  JcustomerMapper jcustomermapper;
    
    
    private static JcustomerUtils jcustomerutils;
    
    @PostConstruct
    public void init() {      
        jcustomerutils = this;  
    }  
    
    public static List<Jcustomer> findJcustomerByPhone(String phone) {
        JcustomerExample example = new JcustomerExample();
        Criteria createCriteria = example.createCriteria();
        createCriteria.andPhoneEqualTo(phone);
        List<Jcustomer> selectByExample = jcustomerutils.jcustomermapper.selectByExample(example );
        return selectByExample;
    }


    
}

 

  如上代碼,可以完成注入。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM