java - Spring @Async 注解的方法在调用自身时会阻塞

标签 java spring asynchronous

在我的软件中,我在 Tomcat 启动时使用 @Async 从后台的 Bean 调用特定方法,这有效正如预期的那样。

但是,在某些定义的情况下,该方法执行的操作会失败,并且方法 myUtil.connect() 会调用自身来重试。

基本代码如下。

bean 定义:

import org.springframework.context.annotation.Bean;
import package.MyService;

@Bean(initMethod = "init", destroyMethod = "destroy")
MyService myService() {
    MyService bean = new MyService();
    return bean;
}

和 MyService bean:

import javax.inject.Inject;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class MyService {

    @Inject
    private MyUtil         myUtil;

    @Async
    public void init() {
        myUtil.connect();
    }
}

我尝试用 @Async 注释方法 connect() ,相信因为它调用自身,@Async 会让它运行也在后台,但没有成功。

有没有办法确保对 connect() 的后续调用“保留”在后台?

编辑:

connect() 制作为真正起作用的函数的包装器是否有效?这样 connect() 只会被调用一次,并且包装的函数将在失败时调用自身。

最佳答案

满足我的要求的工作解决方案如下:

首先,我必须将 @EnableAsync 添加到我的根上下文配置类(这是创建 MyService bean 的配置类)。

然后,我将 @Async 注释从 MyService 移至 MyUtils 类。

MyService 类:

import javax.inject.Inject;
import org.springframework.stereotype.Component;

@Component
public class MyService {

    @Inject
    private MyUtil         myUtil;


    public void init() {
        myUtil.connect();
    }
}

MyUtil 类:

@Component
public class MyUtil {

    @Async
    public void connect() {}

}

文档位于http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html#scheduling-annotation-support-async给出了必要的提示:

To asynchonously initialize Spring beans you currently have to use a separate initializing Spring bean that invokes the @Async annotated method on the target then.

关于java - Spring @Async 注解的方法在调用自身时会阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22465351/

相关文章:

java - 在 JDO 中迁移字段

c# - 在 C# 中反序列化不同类型对象的多个 JSON 数组

c# - 异步调用一个方法然后等待它,有好处吗?

asynchronous - 集成同步和异步库

java - 获取 .Jar 中资源的路径以在 Controller 中使用

java - 为什么我无法捕获 TesseractException?

spring - 如何让多个 Fe​​ignClient-s 使用相同的 serviceId/name?

spring - Mysql-Connector-Java 与 Spring-Jdbc 之间的区别

java - 存在多个构造函数时使用 Autowiring ="constructor"进行依赖注入(inject)?

asynchronous - 当我在 lambda 函数中启动一个新线程并返回时会发生什么