Ped*_*ers 7 spring annotations dependency-injection interface autowired
我正在尝试将@Autowired注释与我的泛型Dao接口一起使用,如下所示:
public interface DaoContainer<E extends DomainObject> {
public int numberOfItems();
// Other methods omitted for brevity
}
Run Code Online (Sandbox Code Playgroud)
我以下列方式在Controller中使用此接口:
@Configurable
public class HelloWorld {
@Autowired
private DaoContainer<Notification> notificationContainer;
@Autowired
private DaoContainer<User> userContainer;
// Implementation omitted for brevity
}
Run Code Online (Sandbox Code Playgroud)
我已使用以下配置配置了应用程序上下文
<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 />
Run Code Online (Sandbox Code Playgroud)
这只是部分工作,因为Spring只创建并注入了我的DaoContainer的一个实例,即DaoContainer.换句话说,如果我问userContainer.numberOfItems(); 我得到了notificationContainer.numberOfItems()的数量
我试图使用强类型接口来标记正确的实现,如下所示:
public interface NotificationContainer extends DaoContainer<Notification> { }
public interface UserContainer extends DaoContainer<User> { }
Run Code Online (Sandbox Code Playgroud)
然后像这样使用这些接口:
@Configurable
public class HelloWorld {
@Autowired
private NotificationContainer notificationContainer;
@Autowired
private UserContainer userContainer;
// Implementation omitted...
}
Run Code Online (Sandbox Code Playgroud)
遗憾的是,这没有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)}
Run Code Online (Sandbox Code Playgroud)
现在,我有点困惑,我应该如何进行或使用多个Dao甚至可能.任何帮助将不胜感激 :)
可以根据需要自动装配尽可能多的 bean。
但是,当您使用按类型自动装配时,它只能是每个接口的 bean 之一。您的错误消息表明您在给定接口的 Spring 容器中没有可用的 bean。
一个办法:
您缺少的 DAO 实现:
@Repository
public class NotificationContainerImpl implements NotificationContainer {}
@Repository
public class UserContainerImpl implements UserContainer {}
Run Code Online (Sandbox Code Playgroud)
您的服务等级:
@Service
public class HelloWorld {
@Autowired
private NotificationContainer notificationContainer;
@Autowired
private UserContainer userContainer;
// Implementation omitted...
}
Run Code Online (Sandbox Code Playgroud)
我将@Configurable注释替换为@Service. @Configurable与 AspectJ 一起使用,这不是您想要的。您必须使用@Component它或它的专业化,例如@Service.
还要记住将所有 Spring 组件放入com.organization.sample包中,以便 Spring 容器能够找到它们。
我希望这有帮助!
| 归档时间: |
|
| 查看次数: |
10289 次 |
| 最近记录: |