在J2EE架构中应用Spring,为了共享WebApp的Spring Context,采用以下方法:
1、新建ContextUtil.java
package
org.readyesb.web.util;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public
class
ContextUtil
...
{
private static ApplicationContext context;

public static ApplicationContext getContext() ...{
if(context==null)...{
context = new ClassPathXmlApplicationContext("applicationContext.xml");
}
return context;
}

public void setContext(ApplicationContext context) ...{
ContextUtil.context = context;
}
}
2、在applicationContext.xml中配置ContextUtil Bean,并指定Singleton作用域
<?
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"
>

<!--
ContextUtil Bean
-->
<
bean
id
="contextUtil"
class
="org.readyesb.web.util.ContextUtil"
scope
="singleton"
/>
</
beans
>
3、扩展org.springframework.web.context.ContextLoaderListener
package
org.readyesb.web.util;
import
javax.servlet.ServletContext;
import
javax.servlet.ServletContextEvent;
import
org.springframework.context.ApplicationContext;
import
org.springframework.web.context.ContextLoaderListener;
import
org.springframework.web.context.support.WebApplicationContextUtils;

public
class
SharedParentContextLoaderListener
extends
ContextLoaderListener
...
{

public void contextInitialized(ServletContextEvent event) ...{
// TODO Auto-generated method stub
super.contextInitialized(event);
ServletContext context = event.getServletContext();
ApplicationContext ctx = WebApplicationContextUtils
.getRequiredWebApplicationContext(context);
ContextUtil contextUtil = (ContextUtil) ctx.getBean("contextUtil");
contextUtil.setContext(ctx);
}
}
4、修改web.xml替换org.springframework.web.context.ContextLoaderListener
<!--
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
-->
<!--
Sharing Spring Parent Context Listener
-->
<
listener
>
<
listener-class
>
org.readyesb.web.util.SharedParentContextLoaderListener
</
listener-class
>
</
listener
>
5、Use like this
ApplicationContext ctx
=
ContextUtil.getContext();
DataProvider dp
=
(DataProvider)ctx.getBean(
"
aopTest
"
);
try
...
{
dp.aopTest();
}
catch
(Exception e)
...
{
e.printStackTrace();
}
关于使用的问题:为什么无法将ContextUtil注入(setter)到EAR中EJB模块的Bean中?
参考: Spirng Use In Other Times
本文介绍如何在J2EE架构下实现Spring上下文的共享,通过创建ContextUtil工具类并配合自定义的SharedParentContextLoaderListener监听器,确保整个Web应用程序能够访问同一Spring上下文实例。
1751

被折叠的 条评论
为什么被折叠?



