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

 

原文地址:https://www.cnblogs.com/ywy8/p/13500624.html