1 Star 0 Fork 0

xiaguangme/guice-demo

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
BillingModule.java 2.54 KB
一键复制 编辑 原始数据 按行查看 历史
xiaguangme 提交于 5年前 . guice-demo
package com.code260.ss.guice.demo.bill;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.matcher.Matcher;
import com.google.inject.matcher.Matchers;
import com.google.inject.name.Names;
public class BillingModule extends AbstractModule {
@Override
protected void configure() {
/**
* 2. 绑定接口到实现类
*/
/**
* LinkedBindings
* 支持 bind(A).to(B) 然后链式的 bind(B).to(C)
* to完之后 还支持in in后面接的是Scope 有Singleton
*/
bind(TransactionLog.class).to(DatabaseTransactionLog.class);
bind(CreditCardProcessor.class).to(GoogleCheckoutProcessor.class);
/**
* 6. 结合Named注解 可以将一个参数绑定一个特定的instance 而不是一个实现类
*/
bind(Integer.class).annotatedWith(Names.named("chargeTimeout")).toInstance(200);
/**
* 4. 对于加了PayPal注解的参数,注入PaypalCreditCardProcessor实现,其余的注入GoogleCheckoutProcessor实现
*/
bind(CreditCardProcessor.class).annotatedWith(PayPal.class).to(PaypalCreditCardProcessor.class);
/**
* 5. 对于加了Named注解 其值为testnamed的地方注入TestNamedCreditCardProcessor实现
*/
bind(CreditCardProcessor.class).annotatedWith(Names.named("testnamed")).to(TestNamedCreditCardProcessor.class);
/**
* 8. 用自定义注解的方式结合bindInterceptor方式完成 本质上是个拦截器 有点类似jfinal的理念
*/
bindInterceptor(Matchers.any(), Matchers.annotatedWith(NonWeekend.class), new NotOnWeekendsInterceptor());
}
/**
* 7. 可以使用Provides注解 主动对外提供创建的bean 有点类似 Spring的@Bean注解,这种方式可以对bean做自定义加工
* 相当于反转了bind的那个动作 同时也可以结合 自定义注解 使用 比如上面的@Paypal 效果相同
* 但是这种方式创建的bean不能参与AOP 因为instance是用户创建的嘛,所以任何额外逻辑编编织不进去了。
* 那怎么解决这个问题,guice在bind后提供了toConstructor方法去指定实现类。
* 这样就连Inject注解都不需要了。因为这个实现类可能是三方提供的
* @return
*/
@Provides
public AlertService provideAlertService() {
RedAlertService redAlertService = new RedAlertService();
redAlertService.setTestAttribute();
return redAlertService;
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/xiaguangme/guice-demo.git
git@gitee.com:xiaguangme/guice-demo.git
xiaguangme
guice-demo
guice-demo
master

搜索帮助