在 Spring 中,很容易自动装配 bean 并使它们在应用程序上下文中的任何位置可用。bean 可以专门用于会话/请求/web 套接字等范围。
我有一个相当独特的场景。我从消息代理收到一条消息,这意味着“控制器”中未收到请求。因此,Spring 不会创建@RequestScope
bean(Spring 中的所有这些逻辑都是基于使用@Controller
/@RequestMapping
注释 /DispatchServlet
处理程序)。AutowireCapableBeanFactory
有没有办法使用 Spring或其他方式在请求范围内创建 bean ?
我想做类似下面的事情,其中将SomeService.handle
能够访问getName()
. RequestScopeBean
目前它抛出了这个异常。
例外:
BeanCreationException: Error creating bean with name '
scopedTarget.getRequestUtils': Scope 'request' is not active for the
current thread; consider defining a scoped proxy for this bean
代码
@Service
public class MyMessagingReceiver implements SomeMessageReceiver {
private final SomeService someService;
@Autowired
public MyMessagingReceiver(final SomeService someService) {
this.someService = someService;
}
public void onMessage(MessageObject messageObject) {
//possible here to use AutowireCapableBeanFactory in inject the RequestScopeBean bean?
someService.handle(messageObject);
}
}
@Service
public class SomeService {
private final RequestScopeBean requestScopeBean;
@Autowired
public SomeService(RequestScopeBean requestScopeBean) {
this.requestScopeBean = requestScopeBean;
}
public void handle(MessageObject messageObject) {
System.out.println(this.requestScopeBean.getName());
}
}
@Configuration
public class BeanDeclarations {
@Bean
@RequestScope
public RequestScopeBean requestScopeBean() {
return new RequestScopeBean();
}
}
public RequestScopeBean {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class Interceptor extends HandlerInterceptorAdapter {
private RequestScopeBean requestScopeBean;
@Autowired
public Interceptor(RequestScopeBean requestScopeBean) {
this.requestScopeBean = requestScopeBean;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String name = request.getHeader("name");
this.requestScopeBean.setName(name);
}
}