2016-04-20 89 views
0

請幫幫我 我是新的spring mvc用戶。在控制器I調用單豆像:spring mvc bean作用域singleton似乎不能正常工作

@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 這樣的系統打印結果:名稱:MYNAME =>這是確定

第二次,我在瀏覽器中輸入url:http://localhost:8080/example/student 系統打印結果如下:name:null

爲什麼?你說過爲每個請求創建一個bean實例? 因此,第一次設置學生的名字是「myname」。第二次,當我再次請求時,如果創建了單個bean實例,學生的名字必須是「myname」,因爲它是在第一次請求中設置的?但在我的情況下,第二次請求似乎是一個新的bean實例被創建?所以name值爲null

非常感謝

+0

如果我刪除 「ApplicationContext的背景= 新的ClassPathXmlApplicationContext(新的String [] {」 MVC-調度-servlet.xml中「}) ;」並使用「@Autowired私人學生」,然後爲每個請求創建一個bean實例。任何想法? –

回答

0

春天是做什麼的,你有確切要求。

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

每次您提出請求時,都會創建父上下文的新實例。因此,你沒有得到一個單身範圍的bean。

當您使用,

@Autowired私人學生學生

沒有創建爲每個請求的上下文。因此,您的bean正在使用單例作用域創建。

0

單例實例意味着應用程序中只有bean的單個實例將由BeanFactory或ApplicationContext等Spring容器創建。

當您將* .xml配置文件提供給BeanFactory或ApplicationContext容器時,它們將讀取指定的bean聲明並默認將它們初始化爲單例。

在你的情況下,你將每個請求的容器指定爲「* student」,因此每個「/ student」實例的請求都將被創建。

研究該鏈接可配置XML文件到Spring容器爲Web應用程序 http://docs.spring.io/autorepo/docs/spring/3.2.x/spring-framework-reference/html/mvc.html

相關問題