【问题标题】:Request scoped bean is not creating请求范围的 bean 未创建
【发布时间】:2017-09-06 20:13:34
【问题描述】:

我不知道我遗漏了什么,检查了所有关于请求范围 bean 创建的链接,但我遗漏了一些东西,这就是请求范围 bean 没有创建的原因。

这是请求范围的 bean 类:

package com.spring.beans;

public class RequestScopedBean 
{
    public RequestScopedBean()
    {
        System.out.println("RequestScopedBean constructor");
    }   
    @Autowired
    HttpServletRequest request;

    public void getSessionId()
    {
        if(request != null)
        {
            System.out.println(request.getSession().getId());
        }
    }
}

Web.xml

<web-app>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>
    <listener>
        <listener-class>com.spring.systemaudit.OESLog4jListener</listener-class>
    </listener>
    <listener>
     <listener-class>se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor</listener-class>
    </listener>  
    <listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
    <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    ...
</web-app>

和根上下文.xml

...
<bean id="requestScopedBean" class="com.spring.beans.RequestScopedBean" scope="request">

</bean>
...

如果我创建scope="singleton",则创建 bean,因为我可以在启动服务器时在控制台上看到 sysout,那么为什么不使用 scope="request"。我错过了什么?

【问题讨论】:

    标签: java spring


    【解决方案1】:

    我猜它已成功创建...但应要求提供。必须在调用使用 bean 的控制器时创建 bean。例如。当您键入 localhost:8080/someRequestMapping 时,您的控制器将被触发,并且如果控制器具有对您的 bean 的引用,它就会被创建。

    默认情况下,引用是一个代理,它根据需要创建请求范围的 bean。

    启动时不存在请求,因此未创建 bean(仅创建代理)

    【讨论】:

    • 但是如果我使用http://localhost:2020/SpringWeb/浏览主页(HomeController),我也看不到控制台上的任何系统输出。
    • 哦,我明白了,我必须在 HomeController 上使用它,例如 context.getBean("requestScopedBean");。我明白了:)
    • 在这方面我能再请你帮忙吗?我已经用@Autowired HttpServletRequest request; 修改了类RequestScopedBean 和一个获取会话ID 的方法,但是当我从控制器使用context.getBean(RequestScopedBean.class).getSessionId(); 调用此方法时,request 对象总是null。 bean 类被修改有问题
    • 因为 HttpServletRequest 不是 bean。检查这个stackoverflow.com/questions/592123/…,但请求仍然不能为空。例如,当您尝试访问来自 Job 的请求时
    • 哦!实际上我在这里想要实现的是我们有一个使用了 2 年的 spring mvc 项目,但是由于一些业务需求,我们希望根据会话中的值查询不同的表而不是当前表。所以 Idea 正在注入请求对象(req .bean) 进入该服务类并检查会话值让我们说如果会话具有值 1 然后查询 Table1 否则 Table2。这样只有查询部分会被修改,而不是服务逻辑。
    猜你喜欢
    • 2019-12-01
    • 1970-01-01
    • 2019-12-10
    • 2012-02-24
    • 2013-01-21
    • 2011-11-11
    • 2012-05-26
    • 2011-08-15
    • 1970-01-01
    相关资源
    最近更新 更多