---
title: "Guice2.0的变化——第二部分 从Guice1.0迁徙到2.0"
author: "kyo100900"
date: "2009-01-14T09:17:50Z"
tags: []
categories: ["企业架构"]
slug: "guice2-0-guice1-0-2-0"
draft: false
lastmod: "2009-01-14T09:18:11Z"
id: 315976
url: "https://superleo.iteye.com/blog/315976"
---

从 Guice1.0 迁徙到 Guice2.0

 

Guice2.0 不完全向下兼容 Guice1.0 ，下面我们慢慢看。如果想看更详细的改变报告，请点击查看 [http://google-guice.googlecode.com/svn/trunk/latest-api-diffs/changes.html](http://google-guice.googlecode.com/svn/trunk/latest-api-diffs/changes.html)

 

[Exception Types]()

 

在 Guice1.0 版本时，当自定义的 provider 抛出一个 unchecked 异常时，有时 Guice 会把该异常进行封装，有时候却又不会。这取决于是否该 provider 是直接通过 Provider.get() 调用呢，还是间接通过注入其它类型的调用。

 

到了 Guice2.0 版本时，不管 provider 或 injection 在任何时候抛出异常， Guice 都会将此再次封装成一个 ProvisionException( 呵呵，这和 Spring 封装 DataAccessException 真是如出一辙啊 ) 。这样的规则就简单多了嘛，使得更加容易的编写容错 (fault-tolerant) 代码。

 

比如说呢，如果 Injector 在创建时出现了问题，那么就会抛出 CreationException 。如果是运行期的配置出现问题，那么你将得到一个 ConfigurationException 。

 

现在 ProvisionException ， ConfigurationException 和 OutOfScopeException 这三个异常都公开了，大家可以自由使用了。

 

 

Abstract Types

 

Guice 并不支持注入抽象类型（ Guice2.0 仍然不支持） 。在 Guice1.0 的时候，因为这原因所抛出的异常信息并不算太友好，现在的 Guice2.0 围绕异常信息有了改观，原来一些潜在的错误现在都会报出相应的异常来了。

 

 

Inner Classes

 

Guice1.0 是支持内部非静态类的构造函数注入的，但这是过去的事了，现在已经不支持啦。 ( 注意：下面的代码只在 Guice1.0 时有效，如果想在 Guice2.0 中通过，得将 FakeFoo 设置为内部静态类 )

 

 

 

 

```
public class FooTest extends TestCase {
  public void testFoo() {
    Foo foo = Guice.createInjector().getInstance(FakeFoo.class)
  }

  class FakeFoo implements Foo {
    @Inject TestFoo() {...}
  }
}
```

 

 

[Keys]()

 

 

如果你现在使用 com.google.inject.Key 话，你会发现 Guice 将基本数据类型 ( 比如说 int.class) 和数组类型 ( 比如说 Integer\[].class) 都规范化了 (canonicalizes) 。现在还可以使用 @Providers 来绑定像 List&lt;?&gt; 这样的通配符了。

 

我简单说说。如果大家使用过 Guice1.0 的话，会发现以下面的代码是错误的：

 

```
assertEquals(Key.get(int.class), Key.get(Integer.class));
```

 

 

现在，在 Guice2.0 中这个问题已经修复了，但是如果你要这么使用：

 

```
assertEquals(TypeLiteral.get(int.class), TypeLiteral.get(Integer.class));
```

 

这样仍然是通过不过的，所以这个只针对 com.google.inject.Key 。

 

 

 

[Annotation Implementations]()

 

Guice2.0 修改了对那些没有属性标注 (filedless annotations) 的处理方式——强制你必须实现 equals() 和 hashCode() 两个方法。如果以前在 Guice1.0 中没有实现这两个方法恰巧又能用，现在注意已经在 Guice2.0 中已经无法正常使用了。

 

 

[Injector.getBinding]()

 

Guice2.0 会在绑定的类或接口无法正常解析时，抛出异常。但原来的老版本 Guice1.0 会简单的返回一个 null 。如果你还是想这么做的话，可以调用 injector.getBindings().get(key) 来实现。

 

 

[SPI Changes]()

 

SourceProviders 已经被 Binder.withSource 和 Binder.skipSources 替代了。这些新的方法相对来说更容易调用和测试，毕竟它们并不需要什么静态初始化 ( static initialization ) 或静态依赖 ( static dependencies ) 之类的了。

 

 

 

 

 

全文完.............