事件驱动设计可以有效降低模块间耦合度。
添加Rribbit依赖
<dependency> <groupId>org.rribbit</groupId> <artifactId>rribbit</artifactId> <version>2.7.0</version> <type>jar</type> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>3.0.5.RELEASE</version> </dependency>
配置Spring
<context:component-scan base-package="com.sipsd" /> <bean id="creator" class="org.rribbit.creation.SpringBeanClassBasedListenerObjectCreator"> <property name="packageNames"> <list> <value>com.sipsd</value> </list> </property> <property name="scanSubpackages" value="true" /> </bean> <bean id="rrb" class="org.rribbit.util.RRiBbitUtil" factory-method="createRequestResponseBusForLocalUse"> <constructor-arg ref="creator" /> <constructor-arg value="true" /> </bean>
Payment java to:
public class Payment implements Serializable {
private static final long serialVersionUID = 7460614839664772877L;
private String paymentId;
private double amount;
private String orderId;
/**
* @return the orderId
*/
public String getOrderId() {
return orderId;
}
/**
* @param orderId
* the orderId to set
*/
public void setOrderId(String orderId) {
this.orderId = orderId;
}
/**
* @return the paymentId
*/
public String getPaymentId() {
return paymentId;
}
/**
* @param paymentId
* the paymentId to set
*/
public void setPaymentId(String paymentId) {
this.paymentId = paymentId;
}
/**
* @return the amount
*/
public double getAmount() {
return amount;
}
/**
* @param amount
* the amount to set
*/
public void setAmount(double amount) {
this.amount = amount;
}
}
Payment Service Interface:
public interface PaymentService {
@Listener(hint = "createPayment")
public Payment createPayment(Payment p);
}
Payment Service Implementation:
@Service("paymentService")
public class PaymentServiceImpl implements PaymentService {
@Override
public Payment createPayment(Payment p) {
System.out.println("create payment");
p.setAmount(90000);
return p;
}
}
测试:
public class TestRbit {
private RequestResponseBus rrb;
@Autowired
PaymentServiceImpl ps;
public static void main(String[] args) {
new TestRbit().testRribbit();
}
private void testRribbit(){
ApplicationContext context = new ClassPathXmlApplicationContext(
"rribbit-appContext.xml");
rrb = (RequestResponseBus) context.getBean("rrb");
Payment p = rrb.send("createPayment", new Payment());
System.out.println(p.getAmount());
}
}