Guice
Guice is a lightweight dependency injection framework for Java 6 and above, brought to you by Google.
Quick Start
Hello World
- jar 的引入
<!-- 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
public interface HelloWorld {
void hello();
}
public class HelloWorldImpl implements HelloWorld {
@Override
public void hello() {
System.out.println("hello world");
}
}
- Test
/**
* 简单绑定使用
*/
@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();
}
单例
- 是单例吗?
/**
* 默认创建的不是单例
*/
@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());
}
- 如何创建单例?
/**
* 单例
*/
@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
@ImplementedBy(HelloWorldAnnotationImpl.class)
public interface HelloWorldAnnotation {
void hello();
}
public class HelloWorldAnnotationImpl implements HelloWorldAnnotation {
@Override
public void hello() {
System.out.println("Hello World Annotation!");
}
}
- Test
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();
}
}