0

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);
}

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

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

SomeCommand鉴于SomeModel无法管理,我如何通过 CDI 获取实例。有没有类似的方法来创建像 Guice 这样的自动布线工厂?

4

0 回答 0