@Component public class EventHandlerFactory implements InitializingBean, ApplicationContextAware { private static final Map<String, EventHandler> HANDLER_MAP = new HashMap<>(16);
private ApplicationContext appContext;
/** * 根据提交类型获取对应的处理器 * * @param type 提交类型 * @return 提交类型对应的处理器 */ public EventHandler getHandler(String type) { return HANDLER_MAP.get(type); }
@Override public void afterPropertiesSet() { // 将 Spring 容器中所有的 EventHandler 注册到 HANDLER_MAP appContext.getBeansOfType(EventHandler.class) .values() .forEach(handler -> HANDLER_MAP.put(handler.getType(), handler)); }
@Component @Order(100) public class FilterBehaviorEmailHandler implements IHandler { @Override public boolean execute(BusinessRequest request) { //省略其他处理逻辑 } } @Component @Order(200) public class FilterExcludeEmailHandler implements IHandler { @Override public boolean execute(BusinessRequest request) { //省略其他处理逻辑 } }
在业务中使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
@Service public class EmailService { private final List<IHandler> handlers; public EmailService(List<IHandler> handlers) { this.handlers = handlers; } public void sendEmail() { //省略其他处理逻辑 for (IHandler handler : handlers) { boolean flag = handler.execute(request); if (!flag) { break; } } } }
避免需要修改多个类的 order 顺序,建议使用三位数。新扩展一个 handle 更方便插入在任意位置。
@Configuration @EnableAsync public class AsyncTaskConfig { @Bean public SimpleAsyncTaskExecutor simpleAsyncTaskExecutor() { return new SimpleAsyncTaskExecutor(); } }