在我的软件中,我在 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() {}
}
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/