做测试时可以手动创建ApplicationContext容器对象。
但是当部署到tomcat里,需要让tomcat去加载配置并创建ApplicationContext容器对象
- jar包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.0.RELEASE</version>
</dependency>
- 在web.xml里配置
<!--全局参数-->
<context-param>
<!--参数名必须是contextConfigLocation,不能修改。ContextLoaderListener会根据这个属性值去加载配置文件-->
<param-name>contextConfigLocation</param-name>
<!--spring主配置文件位置-->
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--spring提供的监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
配置后当tomcat启动时,会加载applicationContext.xml文件创建ApplicationContex对象,并将对象存到ServletContext域中
ApplicationContex对象的获取
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
personService = (PersonService) applicationContext.getBean("personService");