2013-04-25 217 views
0

我想在我的servlet 3.0应用程序中使用范围内的请求。Spring @Scope(“请求”)不适用于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的代理,但行为像原型作用域,它是在每个类中的不同实例,它不通过请求保存任何信息...

任何想法我做错了什么?

编辑:

我已经试过相同的情况下使用Servlet 2.5和web.xml配置,它拼命地工作;)

+0

我不知道你的意思。 – woezelmann 2013-04-25 08:58:32

+0

你用Servlet 3.0和web.xml试过了吗?尝试它也... – 2013-04-25 11:56:53

+0

也尝试改变顺序为'servletContext.addListener(new RequestContextListener()); servletContext.addListener(new ContextLoaderListener(applicationContext));'Listerner命令也可以做一些问题。不是100%确定这是因为这里.. ' – 2013-04-25 12:07:49

回答

0

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

试图注入弹簧组件与@Autowired注释

+0

我认为你不明白我的问题:在一个请求里面是CallerInformation的n个不同实例,每个实例都有自己的(在我的情况下为null)属性值。 – woezelmann 2013-04-25 07:59:24

+0

啊好吧我明白了。 你有没有试过检查是否有多个请求实例? – 2013-04-25 08:07:18

+0

我不认为这是问题所在。 CallerInformaion实例应该是某种CGLIB代理,但它不是。我认为Spring不会评估@Scope或somthink ... – woezelmann 2013-04-25 08:30:34