可以通過以下三種方式加載spring容器,實現bean的掃描與管理:
1、 ClassPathXmlApplicationContext:從類路徑中加載
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-context.xml"); context.start();
2、 FileSystemXmlApplicationContext: 從文件系統加載
FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("E:\\spring-context.xml"); context.start();
3、 XmlWebApplicationContext:從web系統中加載
即把spring容器加載到servlet容器(web容器)中,所以需要在web.xml文件中配置servlet或者listener的方式,實現spring容器的加載
web.xml配置listener方式實現加載:
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-context.xml</param-value> </context-param>
web.xml配置servlet方式實現加載:
<servlet> <servlet-name>springServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:/spring-mvc*.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
注意:
在spring MVC中,一般需要同時使用上面兩種方式,servlet方式負責配置controller等view層,listener方式負責配置service、dao等model層。
關於ContextLoaderListener和DispatcherServlet的關系與區別,可以詳細看看下面的延伸文章(似懂非懂,暫時不做整理):
另外:關於web容器(servlet容器)加載spring容器及關系介紹:在servlet中注入spring的bean,servlet容器和spring容器
4、補充:spring容器初始化使用到的基礎包、類以及作用
-org.springframework.beans
-BeanFactory提供配置結構和基本功能,加載並初始化Bean
-org.springframework.context
-ApplicationContext保存了Bean對象並在Spring中被廣泛使用