gpt4 book ai didi

java - Spring SimpleThreadScope 未在@Components 上正确 Autowiring

转载 作者:行者123 更新时间:2023-11-30 10:09:18 27 4
gpt4 key购买 nike

我有一个 Spring Boot 应用程序,我需要有线程绑定(bind)的 bean。我想要需要使用 Spring 的 SimpleThreadScope 的解决方案。我尝试将它 Autowiring 到 @Components 但根据我打印的日志,看起来 Spring 不会为每个生成的线程创建一个新的 bean。如何正确 Autowiring /配置 bean?

这是我的 Controller

@RestController
public class Controller {
@Autowired
private DummyClass dummyClass;

@Autowired
private DummyService1 svc;

@PostMapping
public Result myPostMethod (@RequestBody Request request) {
LOGGER.info("myPostMethod " + Thread.currentThread().getName() + " " + Integer.toHexString(this.dummyClass.hashCode()));
this.svc.doSomething();

return new Result();
}
}

我的示例服务

@Service
public class DummyService1 {

@Autowired
private DummyClass dummyClass;

@Autowired
private DummyService2 service;

public void doSomething () {
LOGGER.info("doSomething " + Thread.currentThread().getName() + " " + Integer.toHexString(this.dummyClass.hashCode()));

this.service.doSomething2();
}
}

@Service
public class DummyService2 {

@Autowired
private DummyClass dummyClass;

public void doSomething2 () {
LOGGER.info("doSomething2 " + Thread.currentThread().getName() + " " + Integer.toHexString(this.dummyClass.hashCode()));
}
}

我的配置

@Configuration
public class MyConfig implements WebMvcConfigurer {

@Bean
@Scope(value = "thread", proxyMode = ScopedProxyMode.TARGET_CLASS)
public DummyClass dummyClass () {
DummyClass ctx = new DummyClass();
return ctx;
}

@Bean
public static BeanFactoryPostProcessor beanFactoryPostProcessor () {
return new CustomScopeRegisteringBeanFactoryPostProcessor();
}
}

public class CustomScopeRegisteringBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory (ConfigurableListableBeanFactory beanFactory) throws BeansException {
beanFactory.registerScope("thread", new SimpleThreadScope());
}
}

2次执行后的实际输出

myPostMethod http-nio-8080-exec-4 81823b32
doSomething http-nio-8080-exec-4 81823b32
doSomething2 http-nio-8080-exec-4 81823b32

myPostMethod http-nio-8080-exec-8 81823b32
doSomething http-nio-8080-exec-8 81823b32
doSomething2 http-nio-8080-exec-8 81823b32

2次执行后的预期输出

myPostMethod http-nio-8080-exec-4 81823b32
doSomething http-nio-8080-exec-4 81823b32
doSomething2 http-nio-8080-exec-4 81823b32

myPostMethod http-nio-8080-exec-8 9a5170d
doSomething http-nio-8080-exec-8 9a5170d
doSomething2 http-nio-8080-exec-8 9a5170d

我注意到如果我在 DummyClass 中执行一个方法(set 或 get),每个线程都会创建一个新实例。我的问题是,新创建的对象没有被注入(inject)组件(DummyService1 和 DummyService2)

最佳答案

WebApplicationContext.SCOPE_REQUEST 是始终为每个请求提供不同 bean 的 Web 感知范围的一部分

@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)

关于java - Spring SimpleThreadScope 未在@Components 上正确 Autowiring ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53332279/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com