Searching...
Tuesday, 3 June 2014

Spring Asynchronous Execution Example

20:27
Some situations we required asynchronous executions in our applications, for example sending an email, file transfer these kind of scenarios we no need to wait until all the process are completed. In order to achieve this spring provides API to execute methods asynchronously .
In this example we will use @Async annotations to execute method asynchronously.

1. Create a Component class

package com.vinod.test;

import java.util.concurrent.TimeUnit;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class SendEmail {
@Async
public void sendEmail() {
System.out.println("Send email started::::");
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Send email completed::::");

}
}

2. Create a Service class

package com.vinod.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EmailService {
@Autowired
private SendEmail sendEmail;

public void sendEmailviaService() {
sendEmail.sendEmail();
}
}

3.Spring configuration xml

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd">

4.Create a Main class

package com.vinod.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AsynchTest {

public static void main(String[] args) {

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"springcontext.xml");
System.out.println("Calling send mail bean");
EmailService es = ctx.getBean(EmailService.class);
es.sendEmailviaService();
System.out.println("Called send mail bean and request for send email");

}

}

4.Output

Calling send mail beanCalled send mail bean and request for send emailSend email started::::Send email completed::::

0 comments: