【问题标题】:Design: Background thread with a Spring service设计:带有 Spring 服务的后台线程
【发布时间】:2016-09-22 15:11:46
【问题描述】:

我有 Spring 服务,它在执行一些任务后启动后台异步任务。我将任务本身定义为一个组件。 现在,如果我必须使用属于我的启动线程的服务的一些方法。我可以在线程(组件)中自动装配服务,它会起作用。问题是……设计。它带来了一种循环依赖? 我们该如何解决这样的问题?

ServiceA->启动一个ThreadA组件->ThreadA需要调用ServiceA中的一个方法。

【问题讨论】:

    标签: spring service


    【解决方案1】:

    如here 所述,使用@Async 注释方法怎么样

    一个未经测试的例子:

    @Service
    public class MyService {
    
        private final RestTemplate restTemplate;
    
        public String mySyncMethod(){
           return "Hello World";
        }
    
        @Async
        public Future<String> myAsyncMethod() throws InterruptedException {
            return new AsyncResult<>(mySyncMethod());
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      相关资源
      最近更新 更多