- 简介
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. 用注解声明
Google Guice 使用入门
本文介绍Google Guice DI框架的基本使用方法,包括依赖注入的基本概念、接口与实现类的绑定方式、不同类型的注入器以及对象作用域配置等内容。
315

被折叠的 条评论
为什么被折叠?



