使用@Component注解時 @Autowired注入為null怎么解決


問題代碼:

/**
 * 天地圖工具類
 *
 * @author ywy
 * @date 2020-08-12
 */
@Component
public class TmapUtil {

    @Autowired
    private TmapConfiguration tmapConfiguration;

    /**
     * 根據地名獲取經緯度
     *
     * @param addr 查詢關鍵字
     * @author ywy
     * @date 2020-08-12
     * @return Map<String, Object>
     * @throws Exception
     */
    public static Map<String, Object> getCoordinateByAddr(String addr) throws Exception {
        Map<String, Object> coordinate = new HashMap<>();
        tmapConfiguration.XXMethod();// 這里會報錯tmapConfiguration為null
        /*省略代碼*/
        return coordinate;
    }
} 

 

解決代碼:

/** 
 * 天地圖工具類
 *
 * @author ywy
 * @date 2020-08-12
 */
@Component
public class TmapUtil {

    @Autowired
    private TmapConfiguration tmapConfiguration;

  /*添加代碼 begin*/
    private static TmapUtil tmapUtil; 

    @PostConstruct
    public void init(){
        tmapUtil = this;
        tmapUtil.tmapConfiguration = this.tmapConfiguration;
    }
  /*添加代碼 end*/

    /**
     * 根據地名獲取經緯度
     *
     * @param addr 查詢關鍵字
     * @author ywy
     * @date 2020-08-12
     * @return Map<String, Object>
     * @throws Exception
     */
    public static Map<String, Object> getCoordinateByAddr(String addr) throws Exception {
        Map<String, Object> coordinate = new HashMap<>();
     // 更改調用方式
        tmapUtil.tmapConfiguration.XXMethod();// 這里tmapConfiguration作為tmapUtil的屬性調用 不再是null了
        /*省略代碼*/
        return coordinate;
    }
}   

 


免責聲明!

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



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