Hello,
I'm using SpringBoot Starter 2.7.0 and found an issue with the asynchronous call, I also notice a similar issue #20597.
I set@EnableAsync
with AspectJ mode, then I call a method with the @Async
annotation, but the target method runs in the same thread, not asynchronously.
Here is my sample code
Configuration Class
@Configuration
@EnableAsync(mode = AdviceMode.ASPECTJ)
@EnableAspectJAutoProxy
public class AsyncConfiguration {
@Bean
public TaskExecutor getExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(5);
executor.setThreadNamePrefix("async-thread-");
return executor;
}
}
Callee Method
@Component
public class HelloService {
@Async
public void sayHello() {
System.out.println("Callee thread : " + Thread.currentThread().getName());
System.out.println("hello world");
}
}
Caller Code (run in the main thread)
@Component
public class Runner implements ApplicationRunner {
@Autowired
private HelloService service;
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("Caller thread : " + Thread.currentThread().getName());
service.sayHello();
}
}
Print Result
Caller thread : main
Callee thread : main
hello world
From the result, it seems that the sayHello
method does not run in an asynchronous thread.
Here is my pom.xml file, in which I have imported the AspectJ weaver lib.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
</dependencies>
I don't know if I use it correctly. Thanks.
Comment From: mdeinum
This is question for which you shouldn't use the issue tracker but rather StackOverflow, see the guidelines.
That being said, when using ASPECTJ as the mode you have to use either loadtime or compile timeweaving to make it work. Hence you need to do additional work either while loading and specify a javaagent (as explained here in the Spring Framework documentation or you have to do additional work while compiling (as explained in this tutorial.
Comment From: sbrannen
Thanks for getting in touch, but it feels like this is a question that would be better suited to Stack Overflow. As mentioned in the guidelines for contributing, we prefer to use the issue tracker only for bugs and enhancements. Feel free to update this issue with a link to the re-posted question (so that other people can find it) or add some more details if you feel this is a genuine bug.