CDI ambiguous dependency when adding @Named qualif

2019-07-18 05:03发布

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条回答
Root(大扎)
2楼-- · 2019-07-18 05:33

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.

查看更多
登录 后发表回答