我有一个Spring Boot应用程序,我需要有线程绑定的bean。我想要在需要使用Spring的SimpleThreadScope的解决方案。我尝试将其自动装配到@Components,但根据我打印的日志,看起来Spring不会为每个生成的线程创建一个新bean。如何正确地自动接线/配置bean?
这是我的控制人
@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());
}
}
两次执行后的实际输出
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
两次执行后的预期输出
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中执行一个方法(设置或获取),则将为每个线程创建一个新实例。我的问题是,新创建的对象没有注入到组件中(DummyService1和DummyService2)
答案 0 :(得分:1)
WebApplicationContext.SCOPE_REQUEST
是Web Aware Scope的一部分,始终为每个请求提供不同的bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)