spring为ApplicationContext提供的3种实现分别 为:ClassPathXmlApplicationContext,FileSystemXmlApplicationContext和 XmlWebApplicationContext,其中XmlWebApplicationContext是专为Web工程定制的。使用举例如下:
1. FileSystemXmlApplicationContext
eg1. ApplicationContext ctx = new FileSystemXmlApplicationContext("bean.xml"); //加载单个配置文件
eg2.
String[] locations = {"bean1.xml", "bean2.xml", "bean3.xml"};
ApplicationContext ctx = new FileSystemXmlApplicationContext(locations ); //加载单个配置文件
eg3.
ApplicationContext ctx =new FileSystemXmlApplicationContext("D:/project/bean.xml");//根据具体路径加载文件
2. ClassPathXmlApplicationContext
eg1. ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
eg2.
String[] locations = {"bean1.xml", "bean2.xml", "bean3.xml"};
ApplicationContext ctx = new ClassPathXmlApplication(locations);
注:其中FileSystemXmlApplicationContext和ClassPathXmlApplicationContext与BeanFactory的xml文件定位方式一样是基于路径的。
/**
String path = "classpath:applicationContext*.xml";
applicationContext = new ClassPathXmlApplicationContext(path);
**/
3. XmlWebApplicationContext
eg1. ServletContext servletContext = request.getSession().getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
三种实例化bean的方式:
1.使用类构造器实例化
<bean id=“orderService" class="cn.itcast.OrderServiceBean"/>
2.使用静态工厂方法实例化
<bean id="personService" class="cn.itcast.service.OrderFactory" factory-method="createOrder"/>
public class OrderFactory {
public static OrderServiceBean createOrder(){
return new OrderServiceBean();
}
}
3.使用实例工厂方法实例化:
<bean id="personServiceFactory" class="cn.itcast.service.OrderFactory"/>
<bean id="personService" factory-bean="personServiceFactory" factory-method="createOrder"/>
public class OrderFactory {
public OrderServiceBean createOrder(){
return new OrderServiceBean();
}
}