我目前正在開發集成了Hibernate的Spring MVC項目。純Spring MVC部分(DispatcherServlet +請求映射)工作正常。現在,我必須解決的問題非常奇怪:我讀過「使用Hibernate進行Java持久化」,我試圖以與本書中介紹的方式類似的方式設計持久層。也就是說,我設計了兩個並行層次結構:一個用於實現類,另一個用於接口。Spring MVC + Hibernate DAO:無法連接bean
所以,我有一個名爲GenericDaoImpl的抽象類,它實現了GenericDao接口。然後我有一個名爲AdvertisementDaoImpl的具體類,它擴展了GenericDaoImpl並實現了AdvertisementDao接口(它擴展了GenericDao)。
然後,在一個服務bean(標有@Service的類)中,我將自動裝配我的dao類。
這裏是我的問題:
- 自動裝配實現接口一個DAO類,但不伸出我的抽象GenericDaoImpl類:OK
- 自動裝配我AdvertisementDaoImpl實現了AdvertisementDao接口和擴展我的抽象GenericDaoImpl類:導致bean初始化異常。
我在DAO層次結構頂部的抽象類將處理常見CRUD方法的所有樣板代碼。所以,我一定要保留它。
有沒有人有解釋?
這裏是代碼的摘錄:
public abstract class GenericDaoImpl <T, ID extends Serializable> implements BeanPostProcessor, GenericDao<T, ID>{
@Autowired(required=true)
private SessionFactory sessionFactory;
private Session currentSession;
private Class<T> persistentClass;
...
}
@Repository
public class AdvertisementDaoImpl extends GenericDaoImpl<Advertisement, Long> implements AdvertisementDao {
...
public List<Advertisement> listAdvertisementByType(AdvertisementType advertisementType, Class<? extends Good> type) {
return null;
}
}
@Service
public class AdvertisementServiceImpl implements AdvertisementService{
@Autowired(required=false)
private AdvertisementDao advertisementDao;
public List<Advertisement> listAllAdvertisements() {
return null;
}
}
這裏的堆棧跟蹤最相關的部分(至少,我想這是):
嵌套的例外是 org.springframework.beans .factory.BeanCreationException:不能 autowire字段:be.glimmo.service.AdvertisementService be.glimmo.controller.HomeController.advertisementService;嵌套0例外是java.lang.IllegalArgumentException異常:無法設置 be.glimmo.service.AdvertisementService場 be.glimmo.controller.HomeController.advertisementService到 be.glimmo.dao.AdvertisementDaoImpl
這是我的Spring configuration(鏈接pastebin.com):
你必須告訴我們什麼是你所得到的例外。 –
有點偏移,但爲什麼generic dao實現BeanPostProcessor? –
我有我的通用dao實現BeanPostProcessor,以便其持有類型化類的屬性將在bean實例化時初始化。但它主要是爲了測試目的,因爲它絕對沒有必要 – kyiu