SpringBoot静态方法调用Spring容器bean
- Spring容器的依赖注入是依赖set方法,而set方法是实例对象的方法,注入依赖时是无法注入静态成员变量的,在调用的时候依赖的Bean才会为null;
@Autowired
CouponBatchService couponBatchServiceBean;
private static CouponBatchService couponBatchService;
@PostConstruct
public void init(){
couponBatchService = this;
}
public static void test(String test) {
couponBatchService.bind(test);
}
解释
- spring 中一个类的方法被另一个类调用时,不能直接实例化这个类,再调用其中的方法;
也不可以把通过service调用的方法直接定义为静态直接直接类名.方法名调用。
必须使用service注入的方式,用service.方法名去调用这个方法。
因为spring 直接new出的对象,无法自动注入@Autowired进入的spring bean**