Guice

Guice is a lightweight dependency injection framework for Java 6 and above, brought to you by Google.

Users’ guide

入门教程

Quick Start

Hello World

  • jar 的引入
  [xml]
1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/com.google.inject/guice --> <dependency> <groupId>com.google.inject</groupId> <artifactId>guice</artifactId> <version>4.1.0</version> </dependency>
  • HelloWorld.java & implements
  [java]
1
2
3
4
5
public interface HelloWorld { void hello(); }
  [java]
1
2
3
4
5
6
7
8
public class HelloWorldImpl implements HelloWorld { @Override public void hello() { System.out.println("hello world"); } }
  • Test
  [java]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/** * 简单绑定使用 */ @Test public void helloTest() throws Exception { Injector injector = Guice.createInjector(new Module() { @Override public void configure(Binder binder) { binder.bind(HelloWorld.class).to(HelloWorldImpl.class); } }); HelloWorld helloWorld = injector.getInstance(HelloWorld.class); helloWorld.hello(); }

单例

  • 是单例吗?
  [java]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/** * 默认创建的不是单例 */ @Test public void isSingletonTest() { Injector injector = Guice.createInjector(new Module() { @Override public void configure(Binder binder) { binder.bind(HelloWorld.class).to(HelloWorldImpl.class); } }); HelloWorld helloWorld = injector.getInstance(HelloWorld.class); HelloWorld helloWorldTwo = injector.getInstance(HelloWorld.class); Assert.assertEquals(helloWorld.hashCode(), helloWorldTwo.hashCode()); }
  • 如何创建单例?
  [java]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/** * 单例 */ @Test public void singletonTest() { Injector injector = Guice.createInjector(new Module() { @Override public void configure(Binder binder) { binder.bind(HelloWorld.class).to(HelloWorldImpl.class).in(Scopes.SINGLETON); } }); HelloWorld helloWorld = injector.getInstance(HelloWorld.class); HelloWorld helloWorldTwo = injector.getInstance(HelloWorld.class); Assert.assertEquals(helloWorld.hashCode(), helloWorldTwo.hashCode()); }

Annotation

有没有觉得 Injector 代码太多,可以使用注解简化代码。

  • HelloWorldAnnotation.java & implements
  [java]
1
2
3
4
5
6
@ImplementedBy(HelloWorldAnnotationImpl.class) public interface HelloWorldAnnotation { void hello(); }
  [java]
1
2
3
4
5
6
7
public class HelloWorldAnnotationImpl implements HelloWorldAnnotation { @Override public void hello() { System.out.println("Hello World Annotation!"); } }
  • Test
  [java]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class HelloWorldAnnotationImplTest { /** * 依赖于注解的实现 * 1. 可以发现相对于 spring,guice 更加的轻量级。 * 2. 这种写法有个缺点。让接口依赖于实现了。如果有多个实现怎么办? */ @Test public void helloTest() throws Exception { Injector injector = Guice.createInjector(); HelloWorldAnnotation annotation = injector.getInstance(HelloWorldAnnotation.class); annotation.hello(); } }