Home  >  Spring Core

Example of @EnableAsync and @Async in Spring

By Arvind Rai, March 22, 2013
In spring to run asynchronous method, @EnableAsync is used with @Configuration. To run a bean method in asynchronous mode, we need to annotate that method with @Async. Configuration class uses SimpleAsyncTaskExecutor by default.
AppConfig.java
package com.concretepage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
@Configuration
@EnableAsync
public class AppConfig {
	@Bean
	public AsyncTask asyncTask() {
		return new AsyncTask();
	}
}

AsyncTask.java
package com.concretepage;
import org.springframework.scheduling.annotation.Async;
public class AsyncTask {
	@Async
	public void doAsyncTask(){
		System.out.println("do some async task");
	}
} 

AppTest.java
package com.concretepage;
import java.sql.SQLException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class AppTest {
	public static void main(String[] args) throws SQLException {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		ctx.register(AppConfig.class);
		ctx.refresh();
		AsyncTask task= ctx.getBean(AsyncTask.class);
		task.doAsyncTask();
	}
}

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us