【发布时间】:2011-02-20 06:53:06
【问题描述】:
我正在尝试将 @Autowired 注释与我的通用 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 />
这只是部分起作用,因为 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。任何帮助将不胜感激:)
【问题讨论】:
-
我没有看到您的接口的任何实现类。有多少个,它们长什么样?
-
我没有明确的接口实现,因为我希望我可以使用通用 dao 类(即 DaoContainer
)。我可以创建明确的实现(正如 Espen 在他的回答中指出的那样)。这感觉不合理,因为我试图尽可能多地利用 Java 泛型。但是,我确实有 DaoContainerImpl . -
也许stackoverflow.com/questions/502994/… 是一个解决方案
标签: spring interface dependency-injection annotations autowired