web应用中Spring ApplicationContext的动态更新
在web应用中时常需要修改配置,并动态的重新加载ApplicationContext。比如,设置和切换数据库。以下给出一个方法,并通过代码验证可行性。
方法的基本思路是,为WebApplicationContext指定一个上级ApplicationContext,然后需要更新的时候先得到它的引用,再调用refresh方法重新加载。如果直接获得WebApplicationContext实例,重新加载(refresh),得不到预期的效果。
在本示例中,classpath下有一个config.properties文件,定义了derby数据库的属性:
jdbc.driverClassName=org.apache.derby.jdbc.EmbeddedDriver
jdbc.url=jdbc:derby:target/database/helloworld;create=true
jdbc.username=test
jdbc.password=testhibernate.dialect=org.hibernate.dialect.DerbyDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
在spring配置文件中定义了两个config.properties文件位置:
<property name="locations"> <list> <value>classpath:config.properties </value> <value>file:/${user.home}/config.properties </value> </list> </property>
如果没有用户目录下的config.properties文件,则classpath下的生效。这时如果在用户目录下部署了新的config.properties文件,内容是mysql数据库设置:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/mydb?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create
这时通过浏览器访问示例的reload.jsp页面,将调用一个刷新ApplicationContext的方法,将会读取用户目录下的属性文件,从而将hibernate环境从derby数据库切换到mysql数据库下,这个过程不需要重启tomcat或者reload web应用。
reload.jsp中调用的类(spring.WebapplicationContextReloader)主要代码如下:
WebApplicationContext context = WebApplicationContextUtils .getWebApplicationContext(request.getSession() .getServletContext()); if (context.getParent() != null) { ((AbstractRefreshableApplicationContext) context.getParent()) .refresh(); } ((AbstractRefreshableApplicationContext) context).refresh();
上级ApplicationContext,需要这样配置,首先,在web.xml文件中增加一个上下文变量的赋值:
<context-param> <param-name>parentContextKey</param-name> <param-value>mycontext</param-value> </context-param>
用来指明上级ApplicationContext的名字,在这里是mycontext。然后,在classpath的根下,建一个beanRefContext.xml文件,用来创建这个ApplicationContext实例,这里的文件名是规定的,Spring会根据约定找到它。
<bean id="mycontext" class="org.springframework.context.support.ClassPathXmlApplicationContext"> <constructor-arg> <list> <value>services-context.xml</value> </list> </constructor-arg> </bean>
在上面的配置中指明创建这个ApplicationContext所需的配置文件。这样,就实现了一个简单的可动态reload的web环境下的ApplicationContext。
示例的完整代码,见svn:
https://dev.easymorse.com/svn/tutorials/spring/tags/reload.test-1.0
5 Comments to “web应用中Spring ApplicationContext的动态更新”
这篇文章上的评论的 RSS feed TrackBack URI
By Arthur, 2011年07月9日 @ 14:47
这位高手,你能不能把这个源码发到我邮箱啊~~我现在也正在搞着切换数据库的~拜托
By Arthur, 2011年07月9日 @ 14:48
我的邮箱是414038013@qq.com
By Marshal, 2011年07月10日 @ 11:32
这个源代码没有保留。如果保留了我都在博客中说明了,一般放在google code下。
By Arthur, 2011年07月11日 @ 09:39
高手,我真的很需要,有没有办法帮我弄到呢~我已经研究了一个星期了~
By 刘剑勇, 2011年12月18日 @ 16:17
我有个项目需要这样子实现
需要有几个数据库共存(帐套)
启动tomcat 后
登录进入系统时通过选择不同的帐套而调用不同的数据库