CDI Producer and Injection

十年热恋 提交于 2019-12-22 07:01:20

问题


i want to use a producer in my application but i'm stuck at the point, where i'm trying to inject the bean. im getting the famous WELD-001409 error. please lighten up my understanding of cdi producer.

here's my interface:

@Named
    public interface MessageSender {
      void sendMessage();
    }

the bean:

public class EmailMessageSender implements MessageSender {

  @Override
  public void sendMessage() {
    System.out.println("Sending email message");
  }

}

and the producer:

@SessionScoped
public class MessageSenderFactory implements Serializable {

    private static final long serialVersionUID = 5269302440619391616L;

    @Produces
    public MessageSender getMessageSender() {
        return new EmailMessageSender();
    }

}

now i'm injecting the bean:

@Inject 
MessageSender messageSender;

when i'm trying to deploy the project i get the WELD-001409 error and eclipse also is saying that there are multiple injection points.

it works with explicit naming:

@Inject @Named("messageSender")
MessageSender messageSender;

is this naming neccessary?


回答1:


  1. Your EmailMessageSender class implements MessageSender and therefore it is a bean available for injection with type either EmailMessageSender or MessageSender.

  2. Your producer returns a bean of type MessageSender.

  3. Your injection point wants the only bean in the whole application whose type and qualifiers exactly match the type and qualifiers of the injection point.

From one and two you have 2 beans that match a single injection point - therefore that's an ambiguous dependency.

Bottom line, your producer is absolutely pointless (aside from causing the error) in the above example because it simply returns a new instance of EmailMessageSender which is the same exact effect as simply @Inject MessageSender since EmailMessageSender has the default scope @Dependent.



来源:https://stackoverflow.com/questions/18781636/cdi-producer-and-injection

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