有時候咱們想異步地調用某個方法。
好比這個場景:在業務處理完畢後,需給用戶發送通知郵件。因爲郵件發送需調用郵箱服務商,有可能發生阻塞,咱們就能夠異步調用。固然有個前提,即若是郵件發送失敗,不須要提示用戶的。java
<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."); } }
日誌是這樣的web
HowToTest completed. start to do business. end to do business.