2017-02-28 67 views
0

我正在用Spring,Hibernate,JSP和Servlets構建一個應用程序。對於每個表單操作方法,我將值傳遞給Servlet,並且我聲明瞭ApplicationContext來加載所有Servlet中的spring.xml。是否有任何方法可以在Servlet中的一個位置刪除ApplicationContext並獲取所有bean ...在Servlet中初始化ApplicationContext

我宣佈

ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml"); 
Student student = (Student) ac.getBean("student"); 

我宣佈這一切servlets..is有任何中央地方宣佈這個和servlet的得豆..

+1

通常在Spring應用程序中只有Spring DispatcherServlet。處理http請求的實際代碼位於(spring管理的)controllern中。進入這些你注入的依賴關係。你應該重新考慮你的設計。你想要做的不是「像春天一樣」。 [查看文檔](https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html) –

回答

0

讓Spring自動裝配你的bean,無論你需要他們。這是做事的首選方式。如果你不熟悉春季@Autowired註釋,只是做這個 -

  1. 添加到您的東西 - servlet.xml中

    <context:component-scan base-package="you_base_package" /> 
    <mvc:annotation-driven /> 
    

    your_base_package是基礎包,其中包含您的學生 類和其他你想自動裝配(或實例化)的類。

  2. @Component註釋你的學生課程和其他人。

  3. 使用此命令可以在需要時獲取Student和其他人的實例。 @Autowired Student student;