本文最后更新于272 天前,其中的信息可能已经过时,如有错误请发送邮件到[email protected]
职责链设计模式的思想可以看职责链模式。这里只写和Spring结合的使用步骤。
这里只记录我的使用方式
// Spring配置类,这里要注意的是,所有的具体处理器要有@Order(n),n是职责链的调用顺序
@Configuration
@RequiredArgsConstructor
public class ResponsibilityConfiguration {
/* 职责链的接口或者父类 */
private final List<ResponsibilityHandler> handlers;
@Bean(name = "responsibilityHandler")
public ResponsibilityHandler responsibilityChain() {
// 根据@Order注解排序
handlers.sort((h1, h2) -> {
Order o1 = AnnotationUtils.findAnnotation(h1.getClass(), Order.class);
Order o2 = AnnotationUtils.findAnnotation(h2.getClass(), Order.class);
return o1.value() - o2.value();
});
// 组装处理器链
for (int i = 0; i < handlers.size() - 1; i++) {
handlers.get(i).setNext(handlers.get(i + 1));
}
return handlers.get(0);
}
}