这两篇博客基本囊括了Guice所有基本操作:
https://www.cnblogs.com/winton-nfs/p/13958362.html
https://blog.csdn.net/xxxlxy2008/article/details/89736544
对基本操作的补充:
1.被注入的变量不能为static,因为若设置为static,因为Guice是用到某个类时才去创建对象,这时IOC容器还没该对象,则初始化时会报空指针异常,所以测试时也就不能放到main方法中,需要单独弄个类/方法去测试.
但是@Provides
注解的方法可以是静态方法或普通方法
2. 注意Named别导错包
3.Linked Bindings
直接在方法里加参数或者直接new 效果一样
1.
@Provides
CreditCardProcessor provideCreditProcessor()
{
return new CheckoutCreditCardProcessor();
}
这两个效果一样
@Provides
CreditCardProcessor provideCreditProcessor(CheckoutCreditCardProcessor checkoutCreditCardProcessor)
{
return checkoutCreditCardProcessor;
}
2. 链式 Linked bindings can also be chained:
@Provides
CheckoutCreditCardProcessor provideCreditProcessor(CreditProcessor creditProcessor)
{
System.out.println("调用: creditProcessor");
return creditProcessor;
}
@Provides
CreditCardProcessor provideCreditProcessor1(CheckoutCreditCardProcessor checkoutCreditCardProcessor)
{
System.out.println("调用: checkoutCreditCardProcessor");
return checkoutCreditCardProcessor;
}
result:
调用: creditProcessor
调用: checkoutCreditCardProcessor
3.IOC里没有对该类进行声明,这样自动创建自己的类
GuiceDemo guiceDemo=injector.getInstance(GuiceDemo.class);
guiceDemo.send();
// 声明不声明都行,不声明会自动创建
@Provides
GuiceDemo getGuiceDemo()
{
return new GuiceDemo();
}