我正在尝试将 @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。任何帮助将不胜感激 :)