我想创建一个泛型类,它将帮助我减少样板代码。我正在使用Spring 3(MVC)和Hibernate 4。如何实例化泛型spring bean?
类看起来是这样的:
@Repository("AutoComplete")
public class AutoComplete<T extends Serializable> implements IAutoComplete {
@Autowired
private SessionFactory sessionFactory;
private Class<T> entity;
public AutoComplete(Class<T> entity) {
this.setEntity(entity);
}
@Transactional(readOnly=true)
public List<String> getAllFTS(String searchTerm) {
Session session = sessionFactory.getCurrentSession();
return null;
}
public Class<T> getEntity() {
return entity;
}
public void setEntity(Class<T> entity) {
this.entity = entity;
}
}
我实例化的bean是这样的:
IAutoComplete place = new AutoComplete<Place>(Place.class);
place.getAllFTS("something");
如果我运行代码,我得到 “没有发现默认的构造函数” 的异常。
Session session = sessionFactory.getCurrentSession();
这是为什么,我该如何解决这个问题:如果我添加一个默认的构造函数,我在这行获得空指针异常?我猜这个问题是因为bean没有被Spring本身实例化,所以它不能自动装载字段。我想自己实例化bean,但如果可能的话,仍然会对它进行spring管理。
你看过SpringData吗?您不必为存储库编写像这样的泛型类。 –