原代码如下,
代码中我没有在A类上加@Component注解
public class A implements B{
@Autowired
private ApplicationContext applicationContext
/**
* 根据传入的service类型获取泛型父接口IService的真实类型
* @param t
* @param <T>
* @return
*/
private <T> IService<T> getIService(Class t){
if (t != null){
//此处applicationContext本身报错为null
IService<T> service = (IService<T>) applicationContext.getBean(t);
return service;
}else {
return null;
}
}
}
当我添加@Component注解后仍然为null,实现ApplicationContextAware,重写setApplicationContext()方法,从而初始化applicationContext
@Component
@Slf4j
public class A implements B, ApplicationContextAware{
private static ApplicationContext applicationContext;
/**
* 根据传入的service类型获取泛型父接口IService的真实类型
* @param t
* @param <T>
* @return
*/
private <T> IService<T> getIService(Class t){
if (t != null){
//此处applicationContext本身报错为null
IService<T> service = (IService<T>) applicationContext.getBean(t);
return service;
}else {
return null;
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (A.applicationContext == null){
A.applicationContext = applicationContext;
}
}
}