【问题标题】:Spring @Scope("request") does not work with Servlet 3.0Spring @Scope("request") 不适用于 Servlet 3.0
【发布时间】:2013-04-25 07:44:55
【问题描述】:

我正在尝试在我的 servlet 3.0 应用程序中使用范围内的请求。

我使用的不是 web.xml,而是 WebApplicationInitializer 的实现。 onStartup 方法如下所示:

@Override
public void onStartup(ServletContext servletContext) throws ServletException {

    AnnotationConfigWebApplicationContext applicationContext =
            new AnnotationConfigWebApplicationContext();

    applicationContext.setServletContext(servletContext);
    applicationContext.scan("package containing proxy scoped bean and other stuff");

    applicationContext.refresh();        

    servletContext.addListener(new ContextLoaderListener(applicationContext));
    servletContext.addListener(new RequestContextListener());
}

请求范围的 bean 如下所示:

@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS) 
public class CallerInformation {

    private String clientIp;

    public String getClientIp() {
        return clientIp;
    }

    public void setClientIp(String clientIp) {
        this.clientIp = clientIp;
    }
}

现在注入的“CallerInformation”不是CGLIB-proxy,而是像原型作用域一样,它是每个类中的不同实例,它不通过请求保存任何信息...

任何想法我做错了什么?

编辑:

我用 servlet 2.5 和 web.xml 配置尝试了相同的场景,它的工作就像地狱一样;)

【问题讨论】:

  • 我不明白你的意思。
  • 你用 servlet 3.0 和 web.xml 试过了吗?也试试...
  • 另外试试改命令为servletContext.addListener(new RequestContextListener()); servletContext.addListener(new ContextLoaderListener(applicationContext));Listerner命令也可以做一些问题。不是 100% 确定这就是原因.. `
  • 为什么使用 proxyMode = ScopedProxyMode.TARGET_CLASS ?如果您使用 proxyMode=ScopedProxyMode.INTERFACES 它将解决您的问题,它在这个问题中解决了我的问题。 stackoverflow.com/questions/23724716/…

标签: java spring scope servlet-3.0


【解决方案1】:

行为是正确的。 该实例仅存在一个请求。 请参阅this site 了解更多信息。

尝试使用@Autowired 注解注入弹簧组件

【讨论】:

  • 我想你没有理解我的问题:在 ONE 请求中有 n 个不同的 CallerInformation 实例,每个实例都有自己的(在我的情况下为 null)属性值。
  • 啊好吧我明白了。你试过检查是否有多个请求实例吗?
  • 我认为这不是问题所在。 CallerInformaion 实例应该是某种 CGLIB 代理,但它不是。我认为 Spring 不会评估 @Scope 或 somthink...
  • 如何自动接线?构造函数、setter 还是字段?
  • 带有@Inject 注解
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-30
  • 1970-01-01
  • 1970-01-01
  • 2019-03-13
  • 1970-01-01
  • 1970-01-01
  • 2015-03-28
相关资源
最近更新 更多