Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CDI Producer and Injection

Tags:

java

cdi

weld

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?

like image 708
VWeber Avatar asked Sep 13 '13 08:09

VWeber


1 Answers

  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.

like image 78
rdcrng Avatar answered Sep 17 '22 19:09

rdcrng