SpringBoot使用@autowire注入为null的问题

当类不是controller,使用Autowired注入的方法显示为null。这个出现原因其实就是此类是在bean加载之前被调用,或者springboot在加载时没有识别到此类,所以注入为空,要想使此类被识别到,那么就要在启动时被spring识别到,需要将其变为bean对象并被识别到。

不使用Autowired注解,改为如下方式

private IDeviceService deviceService = (IDeviceService) SpringContextUtils.getBean(IDeviceService.class);

将需要调用Spring的Service层的类通过@Component注解为组件加载;通过@Autowired获取Service层的Bean对象;为类声明一个静态变量,方便下一步存储bean对象;通过注解@PostConstruct ,在初始化的时候初始化静态对象和它的静态成员变量,拿到bean对象,静态存储下来,防止被释放。

@Component
public class ThresholdAlarm extends SampleParamJob {

    @Autowired
    private IDeviceService deviceService;
    // 声明一个静态变量,用于存储bean对象
    private static ThresholdAlarm thresholdAlarm ;

    @PostConstruct
    public void init() {
        System.out.println("@PostConstruct方法被调用");
        thresholdAlarm = this;
        thresholdAlarm.deviceService = this.deviceService;
    }

    private List<Device> getDeviceListByProductId(String productId){
        LambdaQueryWrapper<Device> query = new LambdaQueryWrapper<Device>()
                .in(Device::getProductId,productId)
                .in(Device::getDeviceState,"1")
                .orderByDesc(Device::getCreateTime);
        List<Device> deviceList = thresholdAlarm.deviceService.list(query);
        return deviceList;
    }
}

原文链接