Guice

Posted by Bruce Tsai
04/21/2016

果汁框架

Guice 是 Google 開發的一個輕量級的依賴注入框架(IoC),非常小而且快速。Guice 支援 Type Safe,它能夠對建構子,屬性,方法進行注入。

和 Spring 類似,主要使用標註形式來完成依賴注入的過程,而不是像 Spring 一樣主要使用XML(雖然也可以用註解,但是 XML 的配置還是作為 Spring 不可或缺的一部分),Guice 的特點就是足夠輕量級,對於一些對於性能要求(包括啟動速度,運行期等等)要求比較高的應用來講的話,使用 Guice 是一個很好的選擇,Guice 依賴的 Jar 檔很少,對於項目的管理來講也稍微輕鬆一點。缺點也有:Guice 的功能對於企業級的應用仍有許多不足。原始碼的侵入性比較強,依賴關係無法像 XML 那麼直觀的描述。

基礎用法

  • 定義服務
class BillingService {
    private final CreditCardProcessor processor;
    private final TransactionLog transactionLog;

    @Inject
    BillingService(CreditCardProcessor processor,
                   TransactionLog transactionLog) {
        this.processor = processor;
        this.transactionLog = transactionLog;
    }

    public Receipt chargeOrder(PizzaOrder order, CreditCard creditCard) {
        ...
    }
}
  • 配置依賴關係
public class BillingModule extends AbstractModule {
    @Override
    protected void configure() {

        /**
         * This tells Guice that whenever it sees a dependency on a TransactionLog,
         * it should satisfy the dependency using a DatabaseTransactionLog.
         */
        bind(TransactionLog.class).to(DatabaseTransactionLog.class);

        /**
         * Similarly, this binding tells Guice that when CreditCardProcessor is used in
         * a dependency, that should be satisfied with a PaypalCreditCardProcessor.
         */
        bind(CreditCardProcessor.class).to(PaypalCreditCardProcessor.class);
    }
}
  • 取得 bean
public static void main(String[] args) {
    /**
     * Guice.createInjector() takes your Modules, and returns a new Injector
     * instance. Most applications will call this method exactly once, in their
     * main() method.
     */
    Injector injector = Guice.createInjector(new BillingModule());

    /**
     * Now that we've got the injector, we can build objects.
     */
    BillingService billingService = injector.getInstance(BillingService.class);
    ...
}

results matching ""

    No results matching ""