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=test

hibernate.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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM