java轻量级IOC框架Guice

Guice是一款由Google开发的轻量级IoC容器,以其速度、无外部配置和简单易用著称。它支持构造、属性和函数注入,并通过Module进行依赖注册。Guice使用Binder构建依赖配置DSL,结合@Provides、@ImplementedBy等注解实现依赖注入。创建Guice实例后,可以通过Injector获取依赖,实现灵活的依赖管理。
摘要由CSDN通过智能技术生成


Guice是由Google大牛Bob lee开发的一款绝对轻量级的java IoC容器。其优势在于:

  1. 速度快,号称比spring快100倍。
  2. 无外部配置(如需要使用外部可以可以选用Guice的扩展包),完全基于annotation特性,支持重构,代码静态检查。
  3. 简单,快速,基本没有学习成本。

Guice和spring各有所长,Guice更适合与嵌入式或者高性能但项目简单方案,如OSGI容器,spring更适合大型项目组织。

注入方式

在我们谈到IOC框架,首先我们的话题将是构造,属性以及函数注入方式,Guice的实现只需要在构造函数,字段,或者注入函数上标注@Inject,如:

构造注入
public class OrderServiceImpl implements OrderService {
    private ItemService itemService;
    private PriceService priceService;

    @Inject
    public OrderServiceImpl(ItemService itemService, PriceService priceService) {
        this.itemService = itemService;
        this.priceService = priceService;
    }

    ...
}
属性注入
public class OrderServiceImpl implements OrderService {
    private ItemService itemService;
    private PriceService priceService;

    @Inject
    public void init(ItemService itemService, PriceService priceService) {
        this.itemService = itemService;
        this.priceService = priceService;
    }

    ...
}
函数(setter)注入
public class OrderServiceImpl implements OrderService {
    private ItemService itemService;
    private PriceService priceService;

    @Inject
    public void setItemService(ItemService itemService) {
        this.itemService = itemService;
    }

    @Inject
    public void setPriceService(PriceService priceService) {
        this.priceService = priceService;
    } 

    ...
}

Module依赖注册

Guice提供依赖配置类,需要继承至AbstractModule,实现configure方法。在configure方法中我们可以用Binder配置依赖。

Binder利用链式形成一套独具语义的DSL,如:

  • 基本配置:binder.bind(serviceClass).to(implClass).in(Scopes.[SINGLETON | NO_SCOPE]);
  • 无base类、接口配置:binder.bind(implClass).in(Scopes.[SINGLETON | NO_SCOPE]);
  • service实例配置:binder.bind(serviceClass).toInstance(servieInstance).in(Scopes.[SINGLETON | NO_SCOPE]);
  • 多个实例按名注入:binder.bind(serviceClass).annotatedWith(Names.named(“name”)).to(implClass).in(Scopes.[SINGLETON | NO_SCOPE]);
  • 运行时注入:利用@Provides标注注入方法,相当于spring的@Bean。
  • @ImplementedBy:或者在实现接口之上标注@ImplementedBy指定其实现类。这种方式有点反OO设计,抽象不该知道其实现类。

对于上面的配置在注入的方式仅仅需要@Inject标注,但对于按名注入需要在参数前边加入@Named标注,如:

public void configure() {
    final Binder binder = binder();

    //TODO: bind named instance;
    binder.bind(NamedService.class).annotatedWith(Names.named("impl1")).to(NamedServiceImpl1.class);
    binder.bind(NamedService.class).annotatedWith(Names.named("impl2")).to(NamedServiceImpl2.class);
}

@Inject
public List<NamedService> getAllItemServices(@Named("impl1") NamedService nameService1,
                                                 @Named("impl2") NamedService nameService2) {
}

Guice也可以利用@Provides标注注入方法来运行时注入:如

   

   @Provides
   public List<NamedService> getAllItemServices(@Named("impl1") NamedService nameService1,
                                             @Named("impl2") NamedService nameService2) {
    final ArrayList<NamedService> list = new ArrayList<NamedService>();
    list.add(nameService1);
    list.add(nameService2);
    return list;
}

Guice实例

下面是一个Guice module的实例代码:包含大部分常用依赖配置方式。更多代码参见github .

package com.github.greengerong.app;

/**
 * ***************************************
 * *
 * Auth: green gerong                     *
 * Date: 2014                             *
 * blog: http://greengerong.github.io/    *
 * github: https://github.com/greengerong *
 * *
 * ****************************************
 */
public class AppModule extends AbstractModule {
    private static final Logger LOGGER = LoggerFactory.getLogger(AppModule.class);
    private final BundleContext bundleContext;

    public AppModule(BundleContext bundleContext) {
        this.bundleContext = bundleContext;
        LOGGER.info(String.format("enter app module with: %s", bundleContext));
    }

    @Override
    public void configure() {
        final Binder binder = binder();
        //TODO: bind interface
        binder.bind(ItemService.class).to(ItemServiceImpl.class).in(SINGLETON);
        binder.bind(OrderService.class).to(OrderServiceImpl.class).in(SINGLETON);
        //TODO: bind self class(without interface or base class)
        binder.bind(PriceService.class).in(Scopes.SINGLETON);


        //TODO: bind instance not class.
        binder.bind(RuntimeService.class).toInstance(new RuntimeService());

        //TODO: bind named instance;
        binder.bind(NamedService.class).annotatedWith(Names.named("impl1")).to(NamedServiceImpl1.class);
        binder.bind(NamedService.class).annotatedWith(Names.named("impl2")).to(NamedServiceImpl2.class);
    }

    @Provides
    public List<NamedService> getAllItemServices(@Named("impl1") NamedService nameService1,
                                                 @Named("impl2") NamedService nameService2) {
        final ArrayList<NamedService> list = new ArrayList<NamedService>();
        list.add(nameService1);
        list.add(nameService2);
        return list;
    }
}

Guice的使用

对于Guice的使用则比较简单,利用利用Guice module初始化Guice创建其injector,如:

Injector injector = Guice.createInjector(new AppModule(bundleContext));

这里可以传入多个module,我们可以利用module分离领域依赖。

Guice api方法:

public static Injector createInjector(Module... modules) 

public static Injector createInjector(Iterable<? extends Module> modules) 

public static Injector createInjector(Stage stage, Module... modules)

public static Injector createInjector(Stage stage, Iterable<? extends Module> modules) 

Guice同时也支持不同Region配置,上面的State重载,state支持 TOOL,DEVELOPMENT,PRODUCTION选项;默认为DEVELOPMENT环境。


Tephra旨在构建一个稳定、高效、易于集群、快速扩展JavaEE开发框架。目前,Tephra已经具备了以下特性: 提供类级别的热更新,但仅建议在需要快速修正严重BUG、并且无法立即进行全更新时使用。 提供全冗余方式的缓存,自动在每个节间同步缓存数据,而每个节都仅从本地内存中获取缓存数据,从而提供高效的执行效率,并且当部分节宕机时仍旧能正常提供服务。当然,也允许使用Redis提供统一的中心节缓存。此特性可用于多节负载时提供不停服更新。 提供数据库读写分离、及读负载均衡,并且允许配置多个不同的数据库,甚至允许在运行期间增加新的数据库配置,并自动映射ORM。允许执行标准的SQL或存储过,同时提供了一个简单、轻量的ORM工具,并集成Hibernate、MyBatis为复杂ORM需求提供支持。 提供MongoDB工具实现对NoSQL的支持,支持负载均衡。 提供轻量级、快速响应的控制器,允许设置最大并发峰值,以确保在突如其来的并发攻击后能继续正常提供服务;也允许设置单IP最大并发量,确保小量IP并发攻击时仍能正常提供服务。允许发布为HTTP(S)、WebSocket、Socket服务。 提供JavaScript脚本引擎支持,允许JavaScript与JavaBean自由交互,并且可以发布JavaScript为服务;以及使用Javacript作为复杂规则验证器。 提供Hadoop存取支持。 模块化开发,使用注解简化配置,增强代码可读性与维护性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值