@Service("taskExecutorFactory") public class TaskExecutorFactory implements ApplicationContextAware,InitializingBean { private ApplicationContext context; private static Map<TaskTypeEnum, TaskExecutor> taskExecutorMap = new HashMap<>(); public static TaskExecutor getExecutor(TaskTypeEnum taskTypeEnum) { if (!taskExecutorMap.containsKey(taskTypeEnum)) { throw new RuntimeException("不支持的任务类型:" + taskTypeEnum.getDescription()); } return taskExecutorMap.get(taskTypeEnum); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; } @Override public void afterPropertiesSet() throws Exception { Map<String, TaskExecutor> taskExecutors = context.getBeansOfType(TaskExecutor.class); for (TaskExecutor executor : taskExecutors.values()) { taskExecutorMap.put(executor.taskType(), executor); } } }