[英]autowire Spring repository into generic field (Spring 4, Hibernate 4)
我正在嘗試構建使用許多泛型的可擴展應用程序。 到目前為止,我有代碼:
@Component
@Named
@Scope("session")
@Repository
public interface FrameworkRepository<E extends FrameworkEntity>
extends PagingAndSortingRepository<E, Long> {
}
@Component
@Named
@Scope("session")
@Repository
public interface OrderRepository extends FrameworkRepository<Order> {
}
@Component
@Named
@Scope("session")
public class FrameworkService<R extends FrameworkRepository> implements Serializable {
@Autowired
private R repository;
}
@Component
@Named
@Scope("session")
public class OrderService extends FrameworkService<OrderRepository> {
public OrderService() {
}
}
但是,當我嘗試在Facelets頁面中使用OrderService實例時,消息出現異常:
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [...FrameworkRepository]
found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
我想,根本問題可能是我對泛型的使用。 也許Spring Data(存儲庫)無法通過OrderRepository接口自動全部創建類,或者Spring @Autowired找不到OrderRepository的實例(由Spring Data動態創建)並將其自動連接到通用字段。
我知道在任何時候都可以找到解決方法而無需使用泛型,但這涉及許多不必要的代碼。 泛型可以導致更簡潔的代碼。
我使用的是Hibernate 4.x,Spring 4.x,JPA 2.1。
我必須添加
<jpa:repositories base-package="dk.nmc.imarket.data"
entity-manager-factory-ref="entityManagerFactory">
</jpa:repositories>
在我的applicationContext.xml中,我重新調整了存儲庫中不必要的注釋-它們只是存儲庫,而不是完整的Spring Bean(按名稱和會話)。 到目前為止,它有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.