ApplicationContext的定义为使用的bean工厂,spring的配置文件一般默认为ApplicationContext.xml,如果容器启动时找不到指定的spring配置文件,就会尝试加载这个默认的配置文件。
一、java项目实例化spring ApplicationContex
1)ClassPathXmlApplicationContext:通过类路径加载指定的配置文件
bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"></bean>
</beans>
接口
public interface PersonService {
public void save();
}
实现类
public class PersonServiceBean implements PersonService {
public void save(){
System.out.println("我是save()方法");
}
}
实例化spring配置文件,通过容器获得bean,并调用方法
@Test public void instanceSpring(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); //实例化ApplicationContext,可传一个String数组,加载多个spring配置文件
PersonService personService = (PersonService)ctx.getBean("personService"); //获得bean
personService.save();
}
2)通过本地文件方式实例化:FileSystemXmlApplicationContext
二、javaweb方式
web方式不同于一般的java项目,因为WEB项目的启动是由WEB服务器控制的,所以ApplicationContext容器的实例化工作也要交由WEB服务器来完成。spring提供了两种方式:
1)通过监听器 ContextLoaderListener方式
<!-- 指定Spring的配置文件,多个配置文件以逗号分隔 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config/applicationContext.xml</param-value>
</context-param>
<!-- 指定以Listener方式启动Spring容器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
2)通过servlet ContextLoaderServlet方式
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config/applicationContext.xml</param-value>
</context-param>
<!-- 指定以Servlet方式启动Spring容器 -->
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
监听器优先servlet加载,目前通过listener方式更为主流。