解决Spring与@Autowired和@Qualifier的冲突
我有一个接口
public interface ParentService{}
和两个实现类
@Service("child1service")
public class Child1 implements ParentService{}
@Service("child2service")
public class Child2 implements ParentService{}
现在我的控制器
public class ServeChild1Controller extendds AbstractController{
@Autowired
public ServeChild1Controller(@Qualifier("child1service") ParentService child1service){
super(child1service)
}
同样有 ServeChild2Controller ..
所以当我运行时出现以下错误
ServeChild1Controller 错误:未定义 [com.service.ParentService] 类型的唯一 bean:期望单个匹配 bean,但发现 2 个 child1service、child2service
我正在尝试阅读有关这些注释的更多信息,但无法解析它。 任何指示都会有所帮助 谢谢
I have an interface
public interface ParentService{}
And Two Implementation Class
@Service("child1service")
public class Child1 implements ParentService{}
@Service("child2service")
public class Child2 implements ParentService{}
Now my Controller
public class ServeChild1Controller extendds AbstractController{
@Autowired
public ServeChild1Controller(@Qualifier("child1service") ParentService child1service){
super(child1service)
}
Similarly there is ServeChild2Controller..
So when i run I get the following error
Error for ServeChild1Controller: No unique bean of type [com.service.ParentService] is defined: expected single matching bean but found 2 child1service, child2service
Am trying to read more about these Annotations but not able to resolve it ..
Any pointers will be of help
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了使用特定实例,您需要使用 @Qualifier(id) 提供注释服务,并在构造函数中再次使用 @Qualifier 注释参数,如下所示:
并且您的构造函数:
In order to use a specific instance you need to provide Annotate the service with @Qualifier(id) and in the constructor anotate the parameter with @Qualifier again, as follows:
And you constructor:
在 Spring (beans) 4.3 中,它的工作方式与您在问题中编写的方式完全相同。
我可以给你举一个我最近遇到的实施分组的例子。 Spring 可以根据类型和限定符区分进行自动装配。使用服务名称是不够的,因为它们需要是唯一的,因此最终会出现类型冲突。
例子:
With Spring (beans) 4.3 it works exactly the way you wrote it in your question.
I can give you example with implementation groupping that I faced recently. Spring can autowire based on on type and qualifier distinction. Using service names is not enough as they need to be unique so you would end up with type conflict.
Example:
我认为 @Qualifier 注释可能需要在与 @Autowired 注释相同的级别上提供。
I think the @Qualifier annotation might need to be provided at the same level as the @Autowired annotation.