Guice 学习(二)构造器注入(Constructor Inject)

为了演示下面的支持多参数的构造函数注入,我在这里写了2个接口和其实现类。注意事项写在了程序注释里面。

1、接口 (interface)/* * Creation : 2015年6月30日 */package com.guice.constructorInject;import com.google.inject.ImplementedBy;@ImplementedBy(ServiceImpl.class){();}/* * Creation : 2015年6月30日 */package com.guice.constructorInject;import com.google.inject.ImplementedBy;@ImplementedBy(HelloGuiceImpl.class){();}2、实现类( implementation)package com.guice.constructorInject;{() {System.out.println(“Hello Guice ,this is field inject demo !”);}}package com.guice.constructorInject;import com.google.inject.Singleton;/* * 保证是单例 */{() {System.out.println(“Hello Guice !”);}}3、测试类/* * Creation : 2015年6月30日 */package com.guice.constructorInject;import com.google.inject.Guice;import com.google.inject.Inject;{private Service service;private HelloGuice helloGuice;public Service getService() {return service;}public HelloGuice getHelloGuice() {return helloGuice;}/*** 构造函数注入: 好处:可以保证只有一个地方来完成属性注入,* 可以确保在构造函数中完成一些初始化工作 不足:类的实例化与参数绑定了,限制了实例化类的方式。*//** @Inject* public ConstructorInjectDemo(Service service) {*this.service = service;* }*//** 支持多参数构造函数注入 ,但是必须只有一个构造函数上面标注Inject*/(Service service, HelloGuice helloGuice) {this.service = service;this.helloGuice = helloGuice;}(String[] args) {ConstructorInjectDemo instance = Guice.createInjector().getInstance(ConstructorInjectDemo.class);instance.getService().execute();instance.getHelloGuice().sayHello();}}

输出结果:

Hello Guice ,this is field inject demo ! Hello Guice !

,一起吃早餐,午餐,晚餐。或许吃得不好,

Guice 学习(二)构造器注入(Constructor Inject)

相关文章:

你感兴趣的文章:

标签云: