SpringBoot @Autowired service注入失败

原代码

@Service
public class XdsShowServiceImpl implements IXdsShowService {

    @Autowired
    private ICodeService codeService;

    public JSONObject getBaseData(String region){
            ...
            this.codeService.【相关方法】
    }
    

报错NullPointException,断点排查问题,发现问题出在codeService注入为null。

解决方案如下:

@Service
public class XdsShowServiceImpl implements IXdsShowService {

    @Autowired
    private ICodeService codeService;
    private static XdsShowServiceImpl xdsShowServiceImpl;
      
    //进行初始化bean之前的操作
    @PostConstruct
    public void init(){
        xdsShowServiceImpl = this;
        xdsShowServiceImpl .codeService = this.codeService;
    }

    public JSONObject getBaseData(String region){
            ...
            xdsShowServiceImpl .codeService.【相关方法】
    }
    

说明:
为类声明一个静态变量,方便下一步存储bean对象。

private static XdsShowServiceImpl xdsShowServiceImpl;

通过注解@PostConstruct ,在初始化的时候初始化静态对象和它的静态成员变量codeService,原理是拿到service层bean对象,静态存储下来,防止被释放。

    @PostConstruct
    public void init(){
        xdsShowServiceImpl = this;
        xdsShowServiceImpl .codeService = this.codeService;
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容