#Spring 4 @Async 实例java
这里写一个简单的示例来讲明 Spring 异步任务的 @Async 注解使用;spring
##看下咱们的依赖关系app
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.0.3.RELEASE</version> </dependency>
##在例子中,咱们会用到注解,看下咱们的 spring.xml 文件:异步
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd"> <context:annotation-config /> <context:component-scan base-package="osuya.example"/> <task:annotation-driven /> <bean class="osuya.example.Spring4Tasks" name="spring4Tasks"></bean> </beans>
这个配置文件中,最主要的就是 task的命名空间以及这句 <task:annotation-driven /> 这告诉spring扫描咱们项目中 使用 @Async 和 @Scheduled 的注解async
##首先咱们建立 @Serviceide
>NormalService + NormalServiceImpl >ASyncService + ASyncServiceImpl
##ASyncServiceImpl实现类:code
package osuya.example; import java.util.concurrent.Future; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.stereotype.Service; @Service public class ASyncServiceImpl implements ASyncService { @Autowired NormalService normalService; @Async @Override public Future<Boolean> async() { // Demonstrate that our beans are being injected System.out.println("Managed bean injected: " + (normalService != null)); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("I'm done!"); return new AsyncResult<Boolean>(true); } }
能够看到,在这个异步方法中,咱们使用了 @Async 而且返回了 AsyncResult。component
##如今咱们来看看他是怎么工做的:orm
package osuya.example; import java.util.concurrent.Future; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Spring4Tasks { @Autowired ASyncService asyncService; @Autowired NormalService normalService; public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("/spring.xml"); Spring4Tasks app = context.getBean(Spring4Tasks.class); app.start(); System.exit(0); } public void start() { normalService.notAsync(); Future<Boolean> result = asyncService.async(); for(int i = 0; i < 5; i++) normalService.notAsync(); while(!result.isDone()){ // we wait } } }
##输出结果:xml
Not in a thread
Not in a thread
Not in a thread
Not in a thread
Not in a thread
Not in a thread
Managed bean injected: true
I'm done!