非 spring context使用spring beans
在非spring bean的代码里使用autowred的spring service会出现报错
Autowired members must be defined in the valid spring bean
比如下面的ABC只是一个普通的 class, 直接使用 Autowired 会导致得到的efg其实是个null.
class ABC {
Autowired
EFG efg;
}
但是也有解决方法, 可以在调用方法里直接查询spring context里的beans, 得到需要用到的beans, 然后直接调用.
You can use a BeanUtil class to get any bean that created in Springl
@Service
public class BeanUtil implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static <T> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}
}
Then you can get the bean.
MyBean obj = BeanUtil.getBean(MyBean.class);