我愛熊貓

          導航

          <2025年7月>
          293012345
          6789101112
          13141516171819
          20212223242526
          272829303112
          3456789

          留言簿(1)

          文章分類

          文章檔案

          最新評論

          Spring Ioc 之三 ---guice的ioc實現

          guice也提供ioc實現,據說比sping效率要高。下面來看代碼實現。

          首先service不需要變化。和前面spring中的一樣,一個Helloservcie接口和其實現類HelloServiceImpl。

          不同的是Action的實現。
          GuiceAction:
          public class GuiceHelloAction implements IHelloAction{
          /*
          * 在屬性上設置注入點
          */
          @Inject
          private HelloService helloservice;

          public void sayHello(){
          this.helloservice.sayHello();
          }
          }

          然后就需要設置guice了。guice的設置是建立自己的類,繼承自com.google.inject.Module

          /**
          *
          * @author yoo
          * Hello的綁定模塊
          */
          public class HelloModule implements Module{

          @Override
          public void configure(Binder binder) {
          /*
          * 綁定HelloServiceImpl到HelloService
          */
          binder.bind(IHelloService.class)
          .to(HelloServiceImpl.class)
          .in(Scopes.SINGLETON);
          }

          }

          需要注意的是binder.bind()方法,就是綁定接口與實現類,并可以制定范圍(單例等)。

          最后就是啟動guice,測試代碼。

          public class GuiceMain {

          /**
          * @param args
          */
          public static void main(String[] args) {
          /*
          * 設置guice的注入器
          */
          Injector injector = Guice.createInjector(new HelloModule());
          /*
          * 從guice的注入器中獲取Action
          */
          GuiceHelloAction hello = injector.getInstance(GuiceHelloAction.class);
          hello.sayHello();

          }

          }

          程序輸出:

          Hello!

          回頭我們在看看guice的注入,還支持方法注入和構造器注入。

          構造器注入示例:

          /*
          * 在構造器上設置注入點
          */

          @Inject
          public HelloAction(HelloService helloservice){
          this.helloservice = helloservice ;
          }

          setter注入示例:

          /*
          * 在方法上設置注入點
          */
          @Inject
          public void setHelloservice(HelloService helloservice) {
          this.helloservice = helloservice;
          }

          與某些其他的框架相反,Guice 并沒有給 "setter" 方法任何特殊待遇。
          不管方法有幾個參數,只要該方法含有 @Inject 標注,Guice 就會實施注入,甚至對基類中實現的方法也不例外。

          其它方法注入:

          @Inject
          public void injectHelloservice(IHelloService helloservice) {
          this.helloservice = helloservice;
          }

          posted on 2008-06-07 12:52 flyoo 閱讀(166) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 缙云县| 昭平县| 蕲春县| 景泰县| 房山区| 碌曲县| 临清市| 嘉义县| 建湖县| 塔城市| 台中县| 福清市| 茶陵县| 靖边县| 慈溪市| 镇江市| 罗山县| 兴化市| 临汾市| 饶阳县| 教育| 旬阳县| 长顺县| 嘉鱼县| 绥芬河市| 阿拉善左旗| 贵定县| 湖北省| 葫芦岛市| 林周县| 光泽县| 舟曲县| 龙口市| 渭南市| 永春县| 江北区| 华亭县| 东乌珠穆沁旗| 忻城县| 芮城县| 成武县|