我正在尝试创建一个通用类来帮助我减少样板代码。我为此使用 Spring 3 (MVC) 和 Hibernate 4。
类看起来像这样:
@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,但如果可能的话,仍然可以管理它。