CDI - 如何注入像Guice的Assisted Inject这样的非托管依赖项

时间:2018-04-09 15:44:41

标签: java-ee cdi assisted-inject

Guice有一个很好的扩展名为AssitedInject。有没有办法在Java EE中实现CDI的自动连线工厂?我希望能够获得具有托管和非托管依赖关系的托管实例。

想象一下类似于实现的命令模式:

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 */
    }
}

使用Guice,我可以创建一个提供实例的工厂:

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

我需要将@Assited添加到SomeCommand的构造函数参数model并将CommandFactory注册到注入器:

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

如果无法管理SomeCommand,我如何通过CDI获取SomeModel的实例。是否有类似的方法来创建像Guice一样的自动连线工厂?

0 个答案:

没有答案