問題代碼:
/** * 天地圖工具類 * * @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; } }