有时候我们想异步地调用某个方法。
比如这个场景:在业务处理完毕后,需给用户发送通知邮件。由于邮件发送需调用邮箱服务商,有可能发生阻塞,我们就可以异步调用。当然有个前提,即如果邮件发送失败,不需要提示用户的。
> 版本说明
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.2.14.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.webflow</groupId> <artifactId>spring-webflow</artifactId> <version>2.3.4.RELEASE</version> </dependency> </dependencies>
> 一个简单的异步方法
package service; import java.util.concurrent.TimeUnit; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class BusinessService { @Async public void doBusiness() throws InterruptedException { System.out.println("start to do business."); TimeUnit.SECONDS.sleep(5); System.out.println("end to do business."); } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc" 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.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd"> <!-- 扫描指定包下的组件 --> <context:component-scan base-package="service"/> <!-- 支持异步方法 --> <task:annotation-driven/> </beans>
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import service.BusinessService; public class HowToTest { public static void main(String[] args) throws InterruptedException { ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); BusinessService s = context.getBean("businessService", BusinessService.class); s.doBusiness(); System.out.println("HowToTest completed."); } }
日志是这样的
HowToTest completed. start to do business. end to do business.