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 SomeCommand
s 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?