这个问题心累
springboot 项目 ,突然在@Component注解下@Autowired的类为null的情况,也就是没注入成功,或者说是此类在bean加载之前就被调用了。
试了各种办法,都不好使
解决办法:
@Component public class StationInfoBLL { @Resource CfgDevicetempService cfgDevicetempService; public static StationInfoBLL stationInfoBLL; @PostConstruct public void init() { stationInfoBLL = this; stationInfoBLL.cfgDevicetempService = this.cfgDevicetempService; }
//调用方法
private List<EquipmentInfo> ModelEquipmentToInfo() {
List<CfgDevicetemp> list = stationInfoBLL.cfgDevicetempService.list(queryWrapper);
}
}
* 声明一个此类的静态变量,用以保存bean。
* 使用@PostConstruct注解,将需要注入的类添加到静态变量中。
* 接下来,使用这个静态变量来调用注入类就行了。
@PostConstruct这个注解的具体作用就是:
注解在方法上,表示此方法是在Spring实例化该bean之后马上执行此方法,之后才会去实例化其他bean。
这样在Spring实例化ComponentClass之后,马上执行此方法,初始化StationInfoBLL 静态对象和成员变量CfgDevicetempService
Spring Boot@Component注解下的类无法@Autowired的问题
原文:https://www.cnblogs.com/wiliamzhao/p/13218050.html