首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

Spring札记3-在Web应用中使用DI容器

2012-10-09 
Spring笔记3---在Web应用中使用DI容器1.加载DI容器Spring内置的ContextLoaderListener和ContextLoaderServ

Spring笔记3---在Web应用中使用DI容器

1.加载DI容器

Spring内置的ContextLoaderListener和ContextLoaderServlet辅助类负责DI容器的实例化和销毁工作。

contextConfigLocation上下文参数指定了ContextLoaderListener会读取装载的Spring配置文件,默认为/WEB-INF/applicationContext.xml。

例如在web.xml中配置:

?

?

<context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/classes/applicationContext.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>

?

?如果目标web容器不支持ServletContextListener,则需要配置ContextLoaderServlet。将web.xml中的listener换成

?

?

<servlet><servlet-name>context</servlet-name><servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class><load-on-startup>1</load-on-startup></servlet>

?

?

2. 让Spring管理多个配置文件

两种解决方案:

?a.调整web.xml中的contextConfigLocation上下文参数取值 ,从而引用这些文件集合,可用空格,逗号,分号等隔开,如下:

?

?

<context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/classes/applicationContext.xml,/WEB-INF/classes/sessioncontent.xml</param-value></context-param>

?

?

?b.在新的applicationContext.xml中使用<import/>元素,从而能应用到sessioncontext.xml文件,如下:

?

?

<import resource="sessioncontent.xml">

?

3. Spring内置的WebApplicationContextUtils使用类能定位ContextLoaderListener或ContextLoaderServlet存储在Web应用中的ioc容器,进而访问到宿主在其中的受管bean。

WebApplicationContextUtils继承于ApplicationContext.相关用法代码如下:

?

?

?

public void processSessionContent(HttpSession hs){ServletContext sc = hs.getServletContext();ApplicationContext sc = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);ISessionContent sessioncontent = (ISessionContent)sc.getBean("sessionContent");......}
?

4.国际化和本地化消息资源

ApplicationContext继承的MessageSource是整个国际化消息支持的基础.

例如下配置:

?

?

<bean id="messageSource" name="code">//访问message_en.properties中的消息log.info(aac.getMessage("helloworld",null,Locale.ENGLISH));//访问message_zh_CN.properties中的消息log.info(aac.getMessage("helloworld",null,Locale.CHINA));//访问message_zh_CN.properties中的消息,并传入参数log.info(aac.getMessage("helloworld",new Object[]{"访客"},Locale.CHINA));
?

?

?

?

热点排行