Spring Boot中如何禁用/覆盖Jar包内的AsyncConfigurer Bean
解决Spring Boot中多个AsyncConfigurer Bean冲突的问题
这个问题我之前在项目里也碰到过,核心原因就是Spring的AbstractAsyncConfiguration会严格校验容器中只能存在一个AsyncConfigurer实例,当你的应用和依赖Jar里各定义了一个时,就会触发这个启动报错。下面给你几个实用的解决办法:
方法一:给自定义AsyncConfigurer添加@Primary注解
这是最直接简单的方式,在你自己实现的AsyncConfigurer类上加上@Primary注解,明确告诉Spring:当存在多个同类型Bean时,优先使用你的这个实例。
示例代码:
@Configuration @EnableAsync @Primary // 关键注解,指定优先使用该Bean public class MyCustomAsyncConfigurer implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.setQueueCapacity(25); executor.initialize(); return executor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return new SimpleAsyncUncaughtExceptionHandler(); } }
方法二:直接排除依赖Jar中的AsyncConfigurer Bean
如果不想用@Primary,也可以把Jar包中定义的AsyncConfigurer Bean直接从Spring容器中排除,有两种实现方式:
方式1:通过@SpringBootApplication的exclude属性排除
@SpringBootApplication(exclude = {DependencyAsyncConfigurer.class}) public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } }
这里的DependencyAsyncConfigurer.class需要替换成依赖Jar中实际的AsyncConfigurer实现类的全限定类名。
方式2:通过@ComponentScan的excludeFilters过滤排除
如果Jar里的Bean是通过@Component或@Configuration注解注册的,还可以用过滤规则排除:
@SpringBootApplication @ComponentScan(excludeFilters = { @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = DependencyAsyncConfigurer.class) }) public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } }
方法三:使用@ConditionalOnMissingBean做兼容(可选)
如果你希望自己的Bean仅在Jar包中没有AsyncConfigurer时生效(适合兼容场景,而非强制覆盖),可以添加@ConditionalOnMissingBean注解:
@Configuration @EnableAsync @ConditionalOnMissingBean(AsyncConfigurer.class) public class MyCustomAsyncConfigurer implements AsyncConfigurer { // 实现代码同上 }
不过这个方法在Jar包已存在AsyncConfigurer时不会生效,你的场景更推荐前两种强制覆盖的方案。
内容的提问来源于stack exchange,提问作者Prashant Thorat
相关产品推荐
相关产品推荐

