Google Guice 入门使用

  • 简介

Google Guice是一个轻量级的DI框架,本文介绍简单使用,不涉及AOP相关,版本为Google Guice 3.0.

  • 基本使用
public interface Service {
    void output(String content);
}
public class ServiceImp implements Service {
    @Override
    protected void output(String content) {
        System.out.println(Content);
    }
}
public class BindModule 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(Service .class).to(ServiceImp .class);      
  }  
}  
public class TestGuice {

    @Inject
    private Service service;

    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new BindModule());
        TestGuice testGuice = injector.getInstance(TestGuice.class);
        testGuice.testBase1.output("helloworld");
    }       
}
  • 在自定义的Module类中进行绑定
    a. 绑定接口到实现
    b. 绑定接口到provider
    c. 根据注解绑定到不同实现
    -自己写Annotations方式
    -使用@Named的方式
    d. 绑定到实例
    e. 指定构造函数绑定
    f. 在@Provides方法中进行绑定

  • 注解绑定
    a. @ImplementedBy
    b. @ProvidedBy

  • 注入方式
    a. 构造函数注入
    b. 属性注入
    c. Setter方法注入

  • 对象Scopes
    在默认情况下,每次通过Guice去请求对象时,都会得到一个新的对象,这种行为是通过Scopes去配置的。Scope的配置使得我们重用对象的需求变得可能。目前,Guice支持的Scope有@Singleton, @SessionScoped, @RequestScoped。
    a. 在Module绑定时声明
    b. 用注解声明

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值