我試圖使用@Autowired註解與我的通用DAO接口是這樣的:春3 DI通用DAO接口
public interface DaoContainer<E extends DomainObject> {
public int numberOfItems();
// Other methods omitted for brevity
}
我在下列方式使用該接口在我的控制器:
@Configurable
public class HelloWorld {
@Autowired
private DaoContainer<Notification> notificationContainer;
@Autowired
private DaoContainer<User> userContainer;
// Implementation omitted for brevity
}
我已經配置了我的應用程序上下文中使用以下配置
<context:spring-configured />
<context:component-scan base-package="com.organization.sample">
<context:exclude-filter expression="org.springframework.stereotype.Controller"
type="annotation" />
</context:component-scan>
<tx:annotation-driven />
這隻有partiall y,因爲Spring創建並注入了我的DaoContainer的一個實例,即DaoContainer。換句話說,如果我問了userContainer.numberOfItems();我得到
我試圖使用強類型接口來標記的正確實施這樣notificationContainer.numberOfItems()的數量:
public interface NotificationContainer extends DaoContainer<Notification> { }
public interface UserContainer extends DaoContainer<User> { }
然後使用這些接口是這樣的:
@Configurable
public class HelloWorld {
@Autowired
private NotificationContainer notificationContainer;
@Autowired
private UserContainer userContainer;
// Implementation omitted...
}
可悲的是這未能BeanCreationException:
org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.organization.sample.dao.NotificationContainer com.organization.sample.HelloWorld.notificationContainer; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.organization.sample.NotificationContainer] 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)}
現在,我有點困惑,我應該如何繼續或甚至可能使用多個Dao。任何幫助將不勝感激:)
我沒有看到您的接口的任何實現類。有多少人,他們看起來像什麼? – skaffman 2010-05-17 07:38:01
我沒有明確的接口實現,因爲我希望我可以使用通用的dao類(即DaoContainer)。我可以創建顯式的實現(正如Espen在他的回答中指出的那樣)。這只是不合理,因爲我試圖儘可能多地利用Java泛型。但是,我確實有DaoContainerImpl 。 –
Peders
2010-05-19 05:30:17
也許http://stackoverflow.com/questions/502994/spring-ioc-and-generic-interface-type/511417#511417是一個解決方案 – 2010-08-18 09:38:45