有类SpringComponent
,属于spring组件:
@Component
class SpringComponent{
void xxMethod();
}
现有一个需要new的类NonSpringComponent
,其中要用到SpringComponent
的实例。如果直接@Autowired
引入,会报空指针异常。
class NonSpringComponent{
@Autowired
SpringComponent springComponent;
void yyMethod(){
springComponent.xxMethod(); //此处会报NPE
}
}
是因为NonSpringComponent
不受spring管理,需要加上@Controller/@Service/@Component
等注解才能在其内部用Autowired
引入被Spring管理的类。
那如何在非spring组件中使用spring组件呢?
可用如下方式:
@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);
}
}
在需要用到Spring组件的地方,用getBean
获取实例。如下:
class NonSpringComponent{
void yyMethod(){
SpringComponent springComponent = BeanUtil.getBean(SpringComponent.class);
springComponent .xxMethod(); //此处正常运行
}
}