Guice的github地址:
这个例子很简单,如果会点Guice,那么不需要再往下看了。
简单来说,它是dependeny injection框架,它与Spring相比,作者已经给出了,见
1.添加依赖
List-1 pom.xml中添加如下依赖
com.google.inject guice 4.0
2.定义接口及实现类
2.1 CreditCardProcessor
List-2
/** * @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
List-3
/** * @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
List-4
/** * @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.测试
List-5
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()); }}
List-5的运行结果如下图1所示:
图1 List-5的运行结果