微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何确定Provider <MyFacade>在新的异步线程中返回新的MyFacade?

如何解决如何确定Provider <MyFacade>在新的异步线程中返回新的MyFacade?

我正在尝试使我的myFacadeProvider.get()返回特定于线程的MyFacade。每当我在正常的WebApplication RequestContext中时,此方法都起作用,因为它在整个应用程序中都返回相同的MyFacade。但是,如果我创建一个新线程并执行myFacadeProvider.get(),它将返回WebApplication RequestContext中引用的同一MyFacade,而不是该特定线程的新线程。无论我在哪个线程中,如何使myFacadeProvider.get()返回特定于线程的MyFacade

一些示例代码

@Component
@Scope(value = WebapplicationContext.ScopE_REQUEST)
public class MyFacade {

  @Setter
  private String work = "the main work";
  
  public String doWork() { 
    return work;
  }
}

@Component
public class QueryES {
   @Autowired
   private Provider<MyFacade> myFacadeProvider;

   public void doThings() {
     // This call gets a MyFacade that is thread safe in this scoped context and works as expected
     MyFacade myFacade = myFacadeProvider.get();
     myFacade.doWork(); // returns `the main work`
     myFacade.setWork("the secondary work");
     myFacade.doWork(); // returns `the secondary work`

     // When I spin up a new thread and do the same call it will give me back the same myFacade 
     // that was returned prevIoUsly instead of a new thread specific myFacade
     Future<String> future = getFacadeAsyncDoWork();  // returns `the secondary work` instead of `the main work`

   }
   
   public ListenableFuture<String> getFacadeAsyncDoWork() {
     return new AsyncResult<String>(doQueryWork());
   }

   public String doQueryWork() {
     // Returns same myFacade as above,I want this to return a thread specific provider
     MyFacade asyncMyFacade= myFacadeProvider.get();
     return asyncMyFacade.doWork(); // returns `the secondary work` instead of `the main work`
   }
}

解决方法

您可以使用CustomScopeConfigurer注册自定义范围。 Spring包含SimpleThreadScope实现,但默认情况下不注册。

示例:

import org.springframework.beans.factory.config.CustomScopeConfigurer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.SimpleThreadScope;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class,args);
    }

    @Bean
    public CustomScopeConfigurer customScopeConfigurer() {
        CustomScopeConfigurer configurer = new CustomScopeConfigurer();
        configurer.addScope("thread",new SimpleThreadScope());
        return configurer;
    }
}
@Component
@Scope(value = "thread")
public class MyFacade {

    private final Thread currentThread = Thread.currentThread();

    public String getThreadName() {
        return currentThread.getName();
    }

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。