- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在 Spring MVC 应用程序中,我有一个请求范围的 bean。我把这颗 bean 注入(inject)到某处。在那里,HTTP 请求服务线程可能会生成一个新线程。
但是每当我尝试从新生成的线程访问请求范围的 bean 时,我都会收到 org.springframework.beans.factory.BeanCreationException
(请参阅下面的堆栈跟踪)。
从 HTTP 请求线程访问请求范围的 bean 工作正常。
如何使请求范围的 bean 可用于 HTTP 请求线程生成的线程?
<小时/>运行以下代码片段。然后启动服务器,例如http://example.com:8080 .
当访问http://example.com:8080/scopetestnormal时,每次向该地址发出请求时,counter
都会增加 1(通过记录器输出可注意到)。 :) super !
访问http://example.com:8080/scopetestthread时,每次向该地址发出请求时,都会引发上述异常。 :(。无论选择什么 ScopedProxyMode
,基于 CGLIB 的和都会发生这种情况基于 JDK 动态代理接口(interface)的请求范围 bean
配置文件
package com.example.config
@Configuration
@ComponentScan(basePackages = { "com.example.scopetest" })
public class ScopeConfig {
private Integer counter = new Integer(0);
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public Number counter() {
counter = new Integer(counter.intValue() + 1);
return counter;
}
/* Adding a org.springframework.social.facebook.api.Facebook request-scoped bean as a real-world example why all this matters
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public Facebook facebook() {
Connection<Facebook> facebook = connectionRepository()
.findPrimaryConnection(Facebook.class);
return facebook != null ? facebook.getApi() : new FacebookTemplate();
}
*/
...................
}
Controller 文件
package com.example.scopetest;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.FacebookProfile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ScopeTestController {
//@Inject
//private Facebook facebook;
@Inject
private Number counter;
private static final Logger logger = LoggerFactory
.getLogger(ScopeTestController.class);
@RequestMapping(value = "/scopetestnormal")
public void scopetestnormal() {
logger.debug("About to interact with a request-scoped bean from HTTP request thread");
logger.debug("counter is: {}", counter);
/*
* The following also works
* FacebookProfile profile = facebook.userOperations().getUserProfile();
* logger.debug("Facebook user ID is: {}", profile.getId());
*/
}
@RequestMapping(value = "/scopetestthread")
public void scopetestthread() {
logger.debug("About to spawn a new thread");
new Thread(new RequestScopedBeanAccessingThread()).start();
logger.debug("Spawned a new thread");
}
private class RequestScopedBeanAccessingThread implements Runnable {
@Override
public void run() {
logger.debug("About to interact with a request-scoped bean from another thread. Doomed to fail.");
logger.debug("counter is: {}", counter);
/*
* The following is also doomed to fail
* FacebookProfile profile = facebook.userOperations().getUserProfile();
* logger.debug("Facebook user ID is: {}", profile.getId());
*/
}
}
}
<小时/>
基于 CGLIB 的请求范围 bean 的堆栈跟踪 (proxyMode = ScopedProxyMode.TARGET_CLASS
)
SLF4J: Failed toString() invocation on an object of type [$java.lang.Number$$EnhancerByCGLIB$$45ffcde7]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.counter': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:342)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:33)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.getTarget(Cglib2AopProxy.java:654)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:605)
at $java.lang.Number$$EnhancerByCGLIB$$45ffcde7.toString(<generated>)
at org.slf4j.helpers.MessageFormatter.safeObjectAppend(MessageFormatter.java:304)
at org.slf4j.helpers.MessageFormatter.deeplyAppendParameter(MessageFormatter.java:276)
at org.slf4j.helpers.MessageFormatter.arrayFormat(MessageFormatter.java:230)
at ch.qos.logback.classic.spi.LoggingEvent.<init>(LoggingEvent.java:114)
at ch.qos.logback.classic.Logger.buildLoggingEventAndAppend(Logger.java:447)18:09:48.276 container [Thread-16] DEBUG c.g.s.c.c.god.ScopeTestController - counter is: [FAILED toString()]
at ch.qos.logback.classic.Logger.filterAndLog_1(Logger.java:421)
at ch.qos.logback.classic.Logger.debug(Logger.java:514)
at com.example.scopetest.ScopeTestController$RequestScopedBeanAccessingThread.run(ScopeTestController.java:58)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
at org.springframework.web.context.request.AbstractRequestAttributesScope.get(AbstractRequestAttributesScope.java:40)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:328)
... 14 more
<小时/>
基于 JDK 动态代理接口(interface)的请求范围 bean 的堆栈跟踪 (proxyMode = ScopedProxyMode.INTERFACES
)
Exception in thread "Thread-16" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.facebook': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:342)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:33)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:182)
at $Proxy28.userOperations(Unknown Source)
at com.example.scopetest.ScopeTestController$PrintingThread.run(ScopeTestController.java:61)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
at org.springframework.web.context.request.AbstractRequestAttributesScope.get(AbstractRequestAttributesScope.java:40)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:328)
... 6 more
最佳答案
好的,阅读SimpleThreadScope中的代码Spring 附带的我认为您可以使用 InheritableThreadLocal 创建一个 SimpleInheritableThreadScope相反。
然后只需使用一些 xml 来注册您的自定义范围:
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="thread-inherited">
<bean class="org.mael.spring.context.support.SimpleInheritableThreadScope"/>
</entry>
</map>
</property>
</bean>
这意味着当您创建具有线程继承
范围的bean时,您将可以通过每个线程的副本访问该bean,并且该副本将在您的线程生成的线程中可用,即一个请求范围的 bean,可以在请求线程中生成的线程中使用。
关于spring-mvc - Spring MVC : How to use a request-scoped bean inside a spawned thread?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14986519/
我在这里有我的 javascript 代码: define(['controllers/controllers', 'services/alerts'], function(module) {
的意义是什么scope = scope-token *( SP scope-token ) scope-token = 1*( %x21 / %x23-5B / %x5D-7E ) 在 RFC6749
我是 AngularJS 的新手。我试图找出这两个 Controller 定义之间的区别: app.controller('simpleController', ['$scope', function
似乎所有 Guice 的开箱即用 Scope 实现本质上都是基于线程的(或完全忽略线程): Scopes.SINGLETON和 Scopes.NO_SCOPE忽略线程并且是边缘情况:全局范围和无范围。
如果这个问题涉及的是一个常见问题,我很抱歉,但我发现这个问题非常抽象,并且无法真正为其构建一个好的 Google 搜索词。 我试图理解并找到 Maven 中提供的依赖项的用例。我的想法是这样的: 假设
假设我有以下 Controller angular.module('scopeExample', []) .controller('MyController', ['$scope', func
当前在TmThemeEditor上注册的243种配色方案中, 我注意到几乎没有人使用范围选择器运算符。 对于以下情况,运算符非常有用: (text.html | text.xml) & (meta.t
我有一些行为不符合预期的代码......我在 AngularJS Controller 中有一个事件监听器,如下所示: $scope.$on("newClipSelected", function(e
首先,如果帖子太长,我深表歉意。另外,为了以防万一这会以某种方式干扰您可能给我的答案,我不会以通常的方式定义我的 Controller 。相反,我关注http://www.technofattie.c
我有一个模式,其中许多项目类型都是“可编辑的”。这意味着我有很多模板(每种可编辑项目类型一个),这些模板期望具有唯一的字段,但具有通用功能(编辑、保存、取消编辑、删除等)。这些常见功能导致 Contr
$evalAsync 和 $applyAsync 之间有什么区别?我的理解是,当我从指令中使用 $evalAsync 时,表达式将在浏览器呈现之前进行计算。 举个例子,如果我想滚动到页面上的特定位置但
我试图为一个 $scope 变量提供另一个 $scope 变量的值。有人能告诉我出了什么问题吗?查看简单的 plunker 了解详细信息: http://plnkr.co/edit/TlKnd2fM5
我有以下一段 Angular 代码 $scope.prepare = function(){ $scope.elems = [1,2,3]; }; $scope.action = functio
我正在关注 Angularjs 的官方教程,但我陷入了第 2 步。 这是一个片段,我不明白 $scope:scope 的含义, describe('PhoneListCtrl', function()
根据文档, Global: Component is shared among all users. Session: Separate instances of the component are
显示作用域变量,类似于 Angularjs 中的 ng-repeat 元素 这些是我的范围变量 $scope.published = true; $scope.count = 3; 我还有一个名为 l
我是 Angular 的新手,我想在普通的 javascript 中做一些非常简单的事情,但我无法找到如何在 Angular 中正确地做到这一点! 我想设置一个通用函数来清除输入文本字段: 我有这个
在article中发现了这样一个idea : Notice how the value function takes the scope as parameter (without the $ in
注释部分将位于 $scope.$on 下。我需要将 options 返回到我保存 $scope.$emit 的地方。请帮助!!! if (gridConfig.Batch) {
我有一个带有 2 个作用域的 Controller : app.controller('search', function($scope) { $scope.value1 = '';
我是一名优秀的程序员,十分优秀!