【发布时间】: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