Spring的@Async

,但是有些小地方他又不给你很清楚的说明。

  • 要获得异步,加@Async即可
  • 如果要配置连接池,在applicationContext.xml中加入

<task:executor id="WhifExecutor" pool-size="10"/>

<task:annotation-driven executor="WhifExecutor" />

注意: 使用连接池的情况下,applicationContext.xml配置文件需要加入命名空间

xmlns:task="http://www.springframework.org/schema/task"

http://www.springframework.org/schema/task

http://www.springframework.org/schema/task/spring-task.xsd

  • 最重要的事情,很多异步无法成的原因如下:

异步方法需要在另外一个service里面才行

如下:

失败的例子:

@Service
public class AsyncTest{

    public void dodd(){
        System.out.println("1");
        doSomeThing();
        System.out.println("3");
    }
    
    @Async
    public void doSomeThing(){
        System.out.println("2");
    }
}

成功的例子:

@Service
public class AsyncTest{

    @Resource
    AsyncIface asysncIface;
    
    public void dodd(){
        System.out.println("1");
        asysncIface.doSomeThing();
        System.out.println("3");
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容