栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

以下正是我所要求的。虽然,它没有综合工厂的实现,但它足够好,因为工厂可以访问 注入上下文, 因此可以在构造期间使用其他 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 的默认范围不是(它是原型)。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/470192.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号