这是本教程的第二部分,我们将使用Spring Integration创建发票处理应用程序。 如果您错过了它,一定要看一下第一部分 。 以前,我们已经定义了系统的功能要求,创建了网关,分离器,过滤器和路由器组件。 让我们继续创建一个转换器。
5.将发票转换为付款
现在,我们已经成功地从系统中过滤掉了“过于昂贵”的发票(它们可能需要人工检查等)。 重要的是,我们现在可以收取发票并从中产生付款。 首先,让我们将Payment类添加到银行
包:
package com.vrtoonjava.banking;
import com.google.common.base.Objects;
import java.math.BigDecimal;
public class Payment {
private final String senderAccount;
private final String receiverAccount;
private final BigDecimal dollars;
public Payment(String senderAccount, String receiverAccount, BigDecimal dollars) {
this.senderAccount = senderAccount;
this.receiverAccount = receiverAccount;
this.dollars = dollars;
}
public String getSenderAccount() {
return senderAccount;
}
public String getReceiverAccount() {
return receiverAccount;
}
public BigDecimal getDollars() {
return dollars;
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add('senderAccount', senderAccount)
.add('receiverAccount', receiverAccount)
.add('dollars', dollars)
.toString();
}
}
因为我们将有两种方法(从本地和国外发票)创建付款,所以我们定义一个用于创建付款的通用合同(界面)。 将界面PaymentCreator放入银行业务包:
package com.vrtoonjava.banking;
import com.vrtoonjava.invoices.Invoice;
/**
* Creates payment for bank from the invoice.
* Real world implementation might do some I/O expensive stuff.
*/
public interface PaymentCreator {
Payment createPayment(Invoice invoice) throws PaymentException;
}
从技术上讲,这是一个简单的参数化工厂。 请注意,它将引发PaymentException 。 稍后我们将进行异常处理,但这是简单的PaymentException的代码:
package com.vrtoonjava.banking;
public class PaymentException extends Exception {
public PaymentException(String message) {
super(message);
}
}
现在,我们可以将两个实现添加到发票包中了。 首先,让我们创建LocalPaymentCreator类:
package com.vrtoonjava.invoices;
import com.vrtoonjava.banking.Payment;
import com.vrtoonjava.banking.PaymentCreator;
import com.vrtoonjava.banking.PaymentException;
import org.springframework.integration.annotation.Transformer;
import org.springframework.stereotype.Component;
@Component
public class LocalPaymentCreator implements PaymentCreator {
// hard coded account value for demo purposes
private static final String CURRENT_LOCAL_ACC = 'current-local-acc';
@Override
@Transformer
public Payment createPayment(Invoice invoice) throws PaymentException {
if (null == invoice.getAccount()) {
throw new PaymentExcept