使用@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