Spring XML equivalent of @EnableAsync

后端 未结 3 789
清歌不尽
清歌不尽 2021-01-11 13:48

Is there a way to turn on Spring\'s Async configuration from XML? All the examples I saw are using programmatic context declaration and use @EnableAsync

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-11 14:17

    In the annotation based approach you have to have @EnableAsync on the Configuration class. Something like as shown below:

    @Configuration
    @EnableAsync
    @ComponentScan(basePackages ="com.spring.sample.demoAsync")
    public class SpringAsyncConfig {
    
    }
    

    Then you create a component class to have a function that is called Asynchronously. Something like as shown below:

    @Component
    public class AsyncClass {
    
        @Async
        public Future asyncMethod() {
            System.out.println("Executing Thread Async:" +Thread.currentThread().getName());
            return new AsyncResult(Thread.currentThread().getName());
        }
    }
    

    To have the xml equivalent of this approach, you can create a bean in the applicationContext.xml file as shown below:

    
    

    To call the function asyncMethod() in your flow, you can refer AsyncClass bean from any other bean or service. Below is something that I tried to stitch the flow:

    
       
    
    

    It's not necessary to follow this step but is an alternative approach.

    In my applicationContext.xml file, I also imported the task schema by using:

    xmlns:task="http://www.springframework.org/schema/task
    xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"
    

    and then mentioning the executor as a task in the same file:

    
    

    Now my AsyncClass looks like this without @component annotation.

    public class AsyncClass {
    
        @Async("myexecutor")
        public Future asyncMethod() {
            System.out.println("Executing Thread Async:" +Thread.currentThread().getName());
            return new AsyncResult(Thread.currentThread().getName());
        }
    }
    

    and then finally invoking the asyncMethod() asynchronously from the CallingBeanClass.

提交回复
热议问题