Guice 学习入门
这个例子很简单,如果会点 Guice,那么不需要再往下看了。
简单来说,它是 dependeny injection 框架,它与 Spring 相比,作者已经给出了,见 原文。
1.添加依赖
pom.xml 中添加如下依赖
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>4.0</version>
</dependency>
2.定义接口及实现类
2.1 CreditCardProcessor
/**
* @author dmj1161859184@126.com 2018-09-10 20:00
* @version 1.0
* @since 1.0
*/
public interface CreditCardProcessor {
ChargeResult charge(CreditCard credit, Object amount);
}
/**
* @author dmj1161859184@126.com 2018-09-10 20:42
* @version 1.0
* @since 1.0
*/
public class PaypalCreditCardProcessorImpl implements CreditCardProcessor {
@Override
public ChargeResult charge(CreditCard credit, Object amount) {
LOG.info("charge方法");
return null;
}
}
2.2 TransactionLog
/**
* @author dmj1161859184@126.com 2018-09-10 20:00
* @version 1.0
* @since 1.0
*/
public interface TransactionLog {
void logChargeResult(ChargeResult result);
void logConnectException(Exception e);
}
/**
* @author dmj1161859184@126.com 2018-09-10 20:07
* @version 1.0
* @since 1.0
*/
public class DatabaseTransactionLogImpl implements TransactionLog {
@Override
public void logChargeResult(ChargeResult result) {
LOG.info("logChargeResult方法");
}
@Override
public void logConnectException(Exception e) {
LOG.info("logConnectException方法");
}
}
2.3 BillingService
/**
* @author dmj1161859184@126.com 2018-09-10 19:59
* @version 1.0
* @since 1.0
*/
public interface BillingService {
Receipt chargeOrder(PizzaOrder order, CreditCard credit);
}
/**
* @author dmj1161859184@126.com 2018-09-10 20:00
* @version 1.0
* @since 1.0
*/
public class BillingServiceImpl implements BillingService {
private final CreditCardProcessor processor;
private final TransactionLog transactionLog;
@Inject
public BillingServiceImpl(CreditCardProcessor processor,
TransactionLog transactionLog) {
this.processor = processor;
this.transactionLog = transactionLog;
}
@Override
public Receipt chargeOrder(PizzaOrder order, CreditCard credit) {
try {
ChargeResult result = processor.charge(credit, order.getAmount());
transactionLog.logChargeResult(result);
return result.wasSuccessful()
? Receipt.forSuccessfulCharge(order.getAmount())
: Receipt.forDeclinedCharge(result.getDeclineMessage());
} catch (Exception e) {
transactionLog.logConnectException(e);
return Receipt.forSystemFailure(e.getMessage());
}
}
}
3.测试
public class Main {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new BillingModule());
BillingService billingService = injector.getInstance(BillingService.class);
billingService.chargeOrder(new PizzaOrder(), new CreditCard());
}
}
运行结果如下图所示:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论