【问题标题】:spring mvc bean scope singleton seem not work properlyspring mvc bean 范围单例似乎无法正常工作
【发布时间】:2016-08-12 11:52:03
【问题描述】:

请帮帮我 我是新的 spring mvc 用户。在控制器中,我像这样调用单例 bean:

@RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student(@RequestParam(required = false) String name) {
    ApplicationContext context = 
            new ClassPathXmlApplicationContext(new String[] { "mvc-dispatcher-servlet.xml" });
    Student student = (Student) context.getBean("student");
    if (name != null && name.length() > 1) {
        student.setName(name);
    }
    System.out.println("name:" + student.getName());
    return new ModelAndView("result", "student", student);
}

第一次在浏览器中输入网址:http://localhost:8080/example/student?name=myname 系统打印结果是这样的:name:myname=>没问题

第二次,我在浏览器中输入网址:http://localhost:8080/example/student 系统打印结果如下:name:null

为什么?您说为每个请求创建一个 bean 实例? 所以第一次设置学生的名字是“myname”。第二次,当我再次请求时,如果创建了单个 bean 实例,学生的名字必须是“myname”,因为它是在第一次请求中设置的?但在我的情况下,第二次请求,似乎是一个新的创建bean实例?所以name值为null

非常感谢

【问题讨论】:

  • 如果我删除“ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"mvc-dispatcher-servlet.xml"});”并使用“@Autowired private Student student”,然后为每个请求创建一个 bean 实例。有什么想法吗?

标签: spring-mvc


【解决方案1】:

单实例意味着在整个应用程序中,只有单个 bean 实例将由 Spring 容器(如 BeanFactory 或 ApplicationContext)创建。

当您将 *.xml 配置文件提供给 BeanFactory 或 ApplicationContext 容器时,它们将读取指定的 bean 声明并默认将它们实例化为单例。

在您的情况下,您为每个对“/student”的请求指定您的 *.xml 到容器,因此,对于“/student”实例的每个请求都将被创建。

研究此链接以将您的 xml 文件配置为 web 应用程序的 spring 容器 http://docs.spring.io/autorepo/docs/spring/3.2.x/spring-framework-reference/html/mvc.html

【讨论】:

    【解决方案2】:

    Spring 正在做您所要求的。

    ApplicationContext context = 
                new ClassPathXmlApplicationContext(new String[] { "mvc-dispatcher-servlet.xml" });
    

    每次您发出请求时,您都在创建父上下文的新实例。因此,您没有获得具有单例范围的 bean。

    当你使用时,

    @Autowired 私人学生学生

    您没有为每个请求创建上下文。因此,您的 bean 正在使用单例范围创建。

    【讨论】:

      猜你喜欢
      • 2017-09-04
      • 2012-05-06
      • 2013-02-17
      • 2017-10-09
      • 2017-08-03
      • 2014-05-02
      • 2011-09-11
      • 2016-02-11
      • 1970-01-01
      相关资源
      最近更新 更多