0

Guice has a nice extension called AssitedInject. Is there a way to realise auto-wired factories with CDI in Java EE? I want to be able to obtain managed instances that have managed as well as unmanaged dependencies.

Imagine a Command Pattern like implementation:

public interface Command {
    void execute() throws CommandException;
}

// Could be an EJB with @Stateless handling the Transaction
public class CommandController {
   public void execute(Queue<Command> commandQueue) throws CommandException {
       for (Command command : commandQueue)
           command.execute();
   }
}

public SomeCommand implements Command {

    @Inject 
    private SomeService someService;

    @Inject 
    private OtherService otherService;

    private final SomeModel model;

    public SomeCommand(SomeModel model) {
      this.model = model;
    }

    @Override
    public void execute() throws CommandException { 
      /* Code using someService, otherService and model */
    }
}

With Guice I would be able to create a Factory that would provide the instance:

public interface CommandFactory {
   public SomeCommand create(SomeModel model);
}

I would need to add @Assited to SomeCommands constructor parameter model and register CommandFactory to the injector:

install(new FactoryModuleBuilder()
 .implement(SomeCommand.class, SomeCommand.class)
 .build(CommandFactory.class));

How can I obtain an instance of SomeCommand via CDI given that SomeModel cannot be managed. Is there a similar way to create auto-wired factories like in Guice?

  • Do you mean like a producer annotated with [@javax.enterprise.inject.Produces](https://javaee.github.io/javaee-spec/javadocs/javax/enterprise/inject/Produces.html)? – Steve C Apr 10 '18 at 14:31
  • @SteveC Does it work with @Produces? How would the Producer resolve the injectable dependencies? –  Apr 24 '18 at 10:13

0 Answers0