guice架構的入門使用,guice架構入門使用

來源:互聯網
上載者:User

guice架構的入門使用,guice架構入門使用

guice架構是一種類似於spring的ioc容器的一種架構,使用簡單,比較輕量級的一個架構,速度極快,靈活性極強,現在就先來寫幾個guice的程式。

        在這裡我就不給出guice的jar包,這些都可以比較容易地下載到。 

這裡與spring相同,必須先要有介面及其實作類別才能實現注入。程式為:

介面HelloGuice:

package cn.com.guice;/** * Created by xiaxuan on 15/7/10. */public interface HelloGuice {    public void sayHello();}
實作類別:

package cn.com.guice.impl;import cn.com.guice.HelloGuice;/** * Created by xiaxuan on 15/7/10. */public class HelloGuiceImpl implements HelloGuice{    @Override    public void sayHello() {        System.out.println("Hello Guice!");    }}

在這裡先使用非註解的形式來進行。

這裡要使用一個module來進行注入和綁定,程式如下:

package cn.com.guice;import cn.com.guice.impl.HelloGuiceImpl;import com.google.inject.Binder;import com.google.inject.Module;/** * Created by xiaxuan on 15/7/10. */public class HelloGuiceModule implements Module{    @Override    public void configure(Binder binder) {        binder.bind(HelloGuice.class).to(HelloGuiceImpl.class);    }}

如此基本就完成了注入,現在來測試這個程式。

測試如下:

package cn.com.guice;import cn.com.guice.HelloGuice;import cn.com.guice.HelloGuiceModule;import com.google.inject.Guice;import com.google.inject.Injector;/** * Created by xiaxuan on 15/7/10. */public class TestGuice {    public static void  main(String[] args){        Injector injector= Guice.createInjector(new HelloGuiceModule());        HelloGuice helloGuice=injector.getInstance(HelloGuice.class);        helloGuice.sayHello();    }}

測試結果為:

如此便完成了di的依賴注入思想。



著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.