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

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" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename">
<value>test/messge</value>
</property>

<property name="parentMessgeSource">
<ref="parentMessageSource">  <!--在定义的属性文件中找不到需要的属性键,Spring就会到指定的父实现中去查找 -->
</property>

</bean> 

<bean id="parentMessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename">
<value>parenthelloworld</value>
</property>

<property name="cacheSeconds">
<value>10</value>
</property>

</bean> 

 

其中,basename用于指定.properties属性文件所在的classpath,如存在若干属性文件,则可使用basenames属性(String[]).下面是测试访问属性文件中的消息:

 

 

//访问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));