最近在做系统改造的时候,还遇到了一个问题是,如何集成Spring Struts2和Hessian。
当配置Spring和Struts2的时候,在web.xml做了如下配置:1
2
3
4
5
6
7
8
9<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring/*.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
通过设置listener加载Spring的上下文环境,并在struts.xml中设置对象工厂为Spring:1
<constant name="struts.objectFactory" value="spring" />
这样,Struts2就可以使用Spring上下文环境中的action bean了。
但在配置Hessian的时候,以前在web.xml中是这样配置的:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15<servlet>
<servlet-name>Remoting</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring/*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Remoting</servlet-name>
<url-pattern>/remoting/*</url-pattern>
</servlet-mapping>
在初始化Hessian的servlet的时候又一次把Spring配置文件作为参数,这样又会重新生成一个Spring上下文环境,导致Spring中bean的重复。
为了解决这个问题,在配置Hessian时,做了一下修改,如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16<servlet>
<servlet-name>Remoting</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<!-- <param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring/*.xml</param-value> -->
<!-- 该servlet的spring上下文采用WebApplicationContext,不再重复生成上下文 -->
<param-name>contextAttribute</param-name>
<param-value>
org.springframework.web.context.WebApplicationContext.ROOT
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
即在初始化Hessian时不再传入Spring配置文件,而是传入通过listener初始化的Spring WebApplicationContext上下文环境,即使用同一个上下文环境。