CDI ambiguous dependency when adding @Named qualifier to existing bean via @Produces

冷暖自知 提交于 2019-12-23 23:07:04

问题


I have a CDI bean implementation in a dependency jar file:

@ApplicationScoped
public class MyService {
  public String doSomething() {...}
}

In my webapp, I want to access that service via EL Expression, therefore I have to give it a @Named annotation. But I cannot add the annotation on the MyService implementation because I don't have the rights to change that code.

Therefore I tried creating a producer like

public class MyServiceProducer {
  @Inject MyService myService;

  @Produces @Named("myService")
  public MyService produceNamedInstance() {
    return myService;
  }
}

This results in a

WELD-001409 - ambiguous dependency for type MyService with qualifiers @Default ... Possible dependencies: - Managed Bean [class ...MyService] with qualifiers [@Any @Default] - Producer Method [myService] with qualifiers [@Default @Named @Any] declared as [...]

How can I add a @Named annotation without touching the original source code?


回答1:


The error is referring to the @Inject MyService. You basically defined a second bean via @Produces MyService which is also injectable as MyService, but you didn't make clear which one exactly you meant to inject via @Inject. So CDI got confused and throws this ambiguous dependency error.

Instead of creating another producer for an already auto-produced bean, you should just extend the existing bean and then name it.

@Named("myService")
public class MyNamedService extends MyService {
    //
}

Noted should be that the scope is already @Inherited, so you don't need to re-define it.



来源:https://stackoverflow.com/questions/38391001/cdi-ambiguous-dependency-when-adding-named-qualifier-to-existing-bean-via-prod

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!