以下正是我所要求的。虽然,它没有综合工厂的实现,但它足够好,因为工厂可以访问 注入上下文, 因此可以在构造期间使用其他 bean
(可注入工件)。它使用基于Java的
@Configuration而不是XML,但是它也可以与XML一起使用。
工厂界面:
public interface Robot {}// Implementation of this is to be injected by the IoC in the Robot instancespublic interface Brain { String think();}public class RobotImpl implements Robot { private final String name_; private final Brain brain_; @Inject public RobotImpl(String name, Brain brain) { name_ = name; brain_ = brain; } public String toString() { return "RobotImpl [name_=" + name_ + "] thinks about " + brain_.think(); }}public class RobotBrain implements Brain { public String think() { return "an idea"; }}// The assisted factory typepublic interface RobotFactory { Robot newRobot(String name);}//这是Spring配置,显示了如何进行辅助注射
@Configurationclass RobotConfig { @Bean @Scope(SCOPE_PROTOTYPE) public RobotFactory robotFactory() { return new RobotFactory() { @Override public Robot newRobot(String name) { return new RobotImpl(name, r2dxBrain()); } }; } @Bean @Scope(SCOPE_PROTOTYPE) public Brain r2dxBrain() { return new RobotBrain(); }}测试代码:
public class RobotTest { @Test public void t1() throws Exception { ApplicationContext ctx = new AnnotationConfigApplicationContext(RobotConfig.class); RobotFactory rf = ctx.getBean(RobotFactory.class); assertThat(rf.newRobot("R2D2").toString(), equalTo("RobotImpl [name_=R2D2] thins about an idea")); }}这完全可以实现Guice的功能。棘手的区别是
Scope。Spring的默认范围是,
Singleton而Guice 的默认范围不是(它是原型)。



