在我当前的项目中,调用此方法时:
public Collection<? extends Object> list_values() throws Exception {
String nome = classe().getSimpleName();
String nome_service = nome+"Service";
String local_service = "com.spring.model."+nome;
Class<?> clazz = Class.forName(local_service.toLowerCase()+"."+nome_service);
Object serv = clazz.newInstance();
Collection<? extends Object> list = (Collection<? extends Object>) serv.getClass().getMethod("lista").invoke(serv);
return list;
}
应用程序触发了由以下错误引起的 InitationTargetException:
Caused by: java.lang.NullPointerException
at com.spring.config.generic.service.basicService.lista(basicService.java:51)
其中 basicService
是存储在变量 clazz
中的类的父类(super class)。
谁能告诉我我在这里做错了什么?创建此类的新实例的正确方法是什么?
ps.:basicService中的第51行放在这个方法里面:
@Transactional
public List<?> lista() {
return dao.findAll();
}
并且成员dao
是这样定义的:
@Autowired
protected Dao<E> dao;
最佳答案
好的,我解决了这个问题,在我的项目中添加了一个名为 ApplicationContextHolder 的类,代码如下:
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static ApplicationContext getContext() {
return context;
}
}
函数list_values(...)
的最终代码是:
public List<?> list_values() throws Exception {
String nome = classe().getSimpleName();
Class<?> clazz = Class.forName("com.spring.model."+nome.toLowerCase()+"."+nome+"Service");
Object object = clazz.newInstance();
ApplicationContextHolder.getContext().getAutowireCapableBeanFactory().autowireBean(object);
return (List<?>) object.getClass().getMethod("lista").invoke(object);
}
关于java - IncationTargetException 尝试创建服务类的新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26699753/