是否有可能以及如何在春季进行辅助注射?

Op *_*kel 12 java spring dependency-injection

在Guice 2或3中,存在所谓的辅助/部分注入.有了这个,Guice为我的对象合成工厂实现(实现我的接口),一些构造函数参数由Guice注入,一些是从上下文提供的.

是否有可能以及如何使用Spring做同样的事情?

Op *_*kel 12

以下完全符合我的要求.虽然它没有综合工厂的实现,但它足够好,因为工厂可以访问注入上下文,因此在构造期间可以使用其他bean(可注入的工件).它使用基于java @Configuration而不是XML,但它也适用于XML.

工厂界面:

public interface Robot {

}

// Implementation of this is to be injected by the IoC in the Robot instances
public 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";
    }
}
Run Code Online (Sandbox Code Playgroud)


// The assisted factory type
public interface RobotFactory {
    Robot newRobot(String name);
}
Run Code Online (Sandbox Code Playgroud)

//这是Spring配置,显示了如何进行辅助注射

@Configuration
class 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

测试代码:

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

}
Run Code Online (Sandbox Code Playgroud)

这实现了Guice的功能.棘手的区别是Scope.Spring的默认范围是,Singleton而Guice不是(它是原型).