Spring @Async Not Working

后端 未结 11 694
北荒
北荒 2020-12-08 06:30

An @Async method in a @Service-annotated class is not being called asynchronously - it\'s blocking the thread.

I\'ve got

11条回答
  •  独厮守ぢ
    2020-12-08 07:13

    Jiří Vypědřík's answer solved my problem. Specifically,

    1. Check if your method annotated with @Async is public.

    Another useful information from Spring tutorials https://spring.io/guides/gs/async-method/:

    Creating a local instance of the FacebookLookupService class does NOT allow the findPage method to run asynchronously. It must be created inside a @Configuration class or picked up by @ComponentScan.

    What this means is that if you had a static method Foo.bar(), calling it in that manner wouldn't execute it in async, even if it was annotated with @Async. You'll have to annotate Foo with @Component, and in the calling class get an @Autowired instance of Foo.

    Ie, if you have a annotated method bar in class Foo:

    @Component
    class Foo { 
       @Async
       public static void bar(){ /* ... */ }
    
       @Async
       public void bar2(){ /* ... */ }
    }
    

    An in your caller class:

    class Test {
    
      @Autowired Foo foo;
    
      public test(){
         Foo.bar(); // Not async
         foo.bar(); // Not async
         foo.bar2(); // Async
      }
    
    }
    

    Edit: Seems like calling it statically also doesn't execute it in async.

    Hope this helps.

提交回复
热议问题