原文地址:https://code.google.com/p/google-guice/wiki/Injections
Injections(各种注入):常见的有构造函数注入,set方法注入,成员变量注入,前面几篇提到过,就说说没有提到的。
Optional Injections(可选择的注入):就是在注入时可以选择使用注入,通过@Inject(optional=true)实现。
public class PayPalCreditCardProcessor implements CreditCardProcessor { private static final String SANDBOX_API_KEY = "development-use-only"; private String apiKey = SANDBOX_API_KEY; @Inject(optional=true) public void setApiKey(@Named("PayPal API key") String apiKey) { this.apiKey = apiKey; }
或者是在成员变量上:
@Inject(optional=true) Date launchDate;
On-demand Injection(按需注入):方法注入或者变量注入可能用在初始化一个已经存在的实例。你可以用Injector.injectMembers API:
public static void main(String[] args) { Injector injector = Guice.createInjector(...); CreditCardProcessor creditCardProcessor = new PayPalCreditCardProcessor(); injector.injectMembers(creditCardProcessor);
Static Injections(静态注入):不推荐,依赖关系不透明和受类的全局状态影响。
@Override public void configure() { requestStaticInjection(ProcessorFactory.class); ... } class ProcessorFactory { @Inject static Provider<Processor> processorProvider; /** * @deprecated prefer to inject your processor instead. */ @Deprecated public static Processor getInstance() { return processorProvider.get(); } }
Automatic Injection(自动注入):自动注入
Guice自动注入有如下情况:
在绑定代码中,实例被传递到toInstance()
在绑定代码中,provider实例被传递到toProvider()