您的位置:首页 > 移动开发

实例化spring容器applicationContext的几种方法

2013-12-03 17:48 281 查看
一、定义web.xml,由web容器自动加载配置文件初始化ApplicationContext实例,用WebApplicationContextUtils.getWebApplicationContext()得到ApplicationContext的引用。 方法1(web.xml)
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>


方法2 (web.xml)
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>SpringContextServlet</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
</web-app>


方法3 在(struts-config.xml)中加载
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation"
value="/WEB-INF/applicationContext.xml,
/WEB-INF/action-servlet.xml"/>
</plug-in>


注:对于方法1,2如果xml配置文件比较多,可进行拆分,然后在applicationContext.xml配置文件加载被拆分的配置文件,通过<import resource=""/>加载被拆分的配置文件,如下:
<?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.0.xsd"> 
<!-- 加载被拆分的Spring配置文件 -->
<import resource="applicationContext-dao.xml"/>
<import resource="applicationContext-service.xml"/>

</beans>


通过web.xml配置,web容器会自动加载context-param中的配置文件初始化ApplicationContext实例,然后就可以在web应用中通过WebApplicationContextUtils.getWebApplicationContext方法获取ApplicationContext的引用 如:
ApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
LoginAction action=(LoginAction)ctx.getBean("action");


编写SpringUtil.java,在构造方法中如下:

二、利用ClassPathXmlApplicationContext加载配置文件实例化applicationContext

如下:

ApplicationContext ac = new ClassPathXmlApplicationContext("/WEB-    INF/applicationContext.xml");


或者
String[] locations = {"bean1.xml", "bean2.xml", "bean3.xml"};
ApplicationContext ac = new ClassPathXmlApplicationContext(locations);
A a = (A)ac.getBean("a");


三、利用FileSystemXmlApplicationContext加载配置文件实例化applicationContext
ApplicationContext ctx = new FileSystemXmlApplicationContext("/WEB-INF/applicationContext.xml");


或者
String[] locations = {"bean1.xml", "bean2.xml", "bean3.xml"};
ApplicationContext ctx = new FileSystemXmlApplicationContext(locations );
A a =(A)ctx.getBean("a");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: