Spring 3: How to call @Async annotated methods from the TaskExecutor

后端 未结 4 1157
说谎
说谎 2020-12-31 09:15

I\'m new to asynchronous task execution in Spring, so please forgive me if this sounds like a silly question.

I read that @Async annotation is introduced from Sprin

4条回答
  •  情歌与酒
    2020-12-31 09:55

    Here's an example of @Async use:

    @Async
    void doSomething() {
        // this will be executed asynchronously
    }
    

    Now call that method from another class and it will run asynchronously. If you want a return value use a Future

    @Async
    Future returnSomething(int i) {
        // this will be executed asynchronously
    }
    

    The relationship between @Async and TaskExecutor is that @Async uses a TaskExecutor behind the scenes. From the docs:

    By default when specifying @Async on a method, the executor that will be used is the one supplied to the 'annotation-driven' element as described above. However, the value attribute of the @Async annotation can be used when needing to indicate that an executor other than the default should be used when executing a given method.

    So to set up a default executor, add this to your spring config

    
    

    Or to use a particular executor for a single use try

    @Async("otherExecutor")
    

    See http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html#scheduling-annotation-support-async

提交回复
热议问题