如何替换Application context定义文件中自定义的property
问题描述:
在Application context定义文件(如xxx-servlet.xml、applicationContext.xml)中,有时需要一些自定义的property,如datasource的定义 
       <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
              <property name="driverClassName"><value>${jdbc.driverClassName}</value></property> 
              <property name="url"><value>${jdbc.url}</value></property> 
              <property name="username"><value>${jdbc.username}</value></property> 
              <property name="password"><value>${jdbc.password}</value></property> 
       </bean> 
或者可能有时还需要Application的根路径或系统变量。 
解决方案:
       使用org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer, 
这个类的设计意图就是为了解决这个问题。它首先使用用户自定义的变量,然后使用系统变量,然后是这个配置文件的变量。 
具体用法:
1.         在配置文件中声明这个类 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
2.         设定参数(可以为空) 
l         location:指定一个properties文件的路径 <property name="location"><value>/WEB-INF/jdbc.properties</value></property> 
l         locations:指定一组properties文件的路径 <property name=" locations ">     <props>         <prop key="jdbc">/WEB-INF/jdbc.properties </prop>         <prop key="conn">/WEB-INF/conn.properties </prop>     </props> </property> 
如果需要Application跟路径,则需要定义Application的根路径,具体步骤如下: 
1.         在web.xml中,添加 
       <context-param> 
              <param-name>webAppRootKey</param-name> 
              <param-value>petclinic.root</param-value> 
       </context-param> 
设置跟路径名称(默认为webapp.root) 
2.         然后声明WebAppRootListener or Log4jConfigListener 
       <listener> 
              <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> 
       </listener> 
或ContextLoaderServlet 
       <servlet> 
              <servlet-name>context</servlet-name> 
              <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class> 
              <load-on-startup>1</load-on-startup> 
       </servlet> 
如果是上边的声明,则Application的根路径变量的写法是${ petclinic.root }  
 
  |