浅析注解 @EnableAsync @Async
平时需要使用多线程的时候,一般是直接新建一个线程,或者创建一个线程池使用。那么有没有更便利的方式呢?Spring Boot提供了默认的线程池实现,只需两个注解即可在项目中使用多线程。
@EnableAsync
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Import({AsyncConfigurationSelector.class}) public @interface EnableAsync { Class<? extends Annotation> annotation() default Annotation.class; boolean proxyTargetClass() default false; AdviceMode mode() default AdviceMode.PROXY; int order() default 2147483647; }
@EnableAsync
只能标注在类上,表示开启异步执行,通常加在启动类上
@Async
@Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Async { String value() default ""; }
@Async
可以标注在类上、方法上。标注在类上时,此类的所有方法都将异步执行,标注在类上时,只有此方法异步执行。且此注解标注的方法不能有返回值,否则执行时将报错。
默认使用的线程池是Spring Boot
提供的SimpleAsyncTaskExecutor
异步方法并不一定生效,如以下情况下
@Async失效的情况
- 异步方法使用static修饰
- 异步类实例没有交给Spring管理(即没有用@Component等注解修饰)
- 异步方法的调用和异步方法在同一个类中
- 没有使用@EnableAsync注解开启异步执行
- @Async修饰的方法有返回值(执行时出错)
分类:
标签:
,
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步