Java Reference
In-Depth Information
LISTING 6‐14: Factory implementation that creates message beans
package com.devchronicles.factory;
import javax.enterprise.inject.Produces;
public class EventProducer {
@Produces
public MessageA messageAFactory(){
return new MessageA();
}
@Produces
public MessageB messageBFactory(){
return new MessageB();
}
}
In this example, you have created two beans: MessageA in Listing 6-12 and A MessageB in Listing 6-13.
You have annotated them with @Alternative , which disables them so that the container does not
attempt to inject their instances when it i nds a matching injection point. You annotate them so the
factory in Listing 6-14 will produce the instances. If you didn't annotate, the container would throw
an exception while loading the application. It would read something like this:
CDI deployment failure:WELD‐001409 Ambiguous dependencies for type [MessageA] . The
ambiguity is caused by the two instances of MessageA that are created: one by the container and the
A
other by the @Produces method. The container doesn't know which instance to inject into the message
member of the EventService . You will see a way to resolve this ambiguity later in the chapter.
LISTING 6‐15: Injecting the beans created by the factory using the @Inject annotation
package com.devchronicles.factory;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.enterprise.event.Event;
import javax.inject.Inject;
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class EventService {
@Inject
private MessageA messageA;
@Inject
private MessageB messageB;
public void startService(){
messageA.setMessage("This is message A");
Search WWH ::




Custom Search