spring对配置属性的读取方式configure way

来源:互联网 发布:变频布林线源码 编辑:程序博客网 时间:2024/06/05 18:29

1.目的:cas在server启动的时候log print比较难懂,研究清楚spring在web容器启动时的配置属性读取机制,加入自己的属性配置。


2.配置方式:

2.1.WEB-INF/spring-configuration是“约定优于配置”选项部署,spring可以自动找到这个路径,不需要修改web.xml,你可以放一个Spring XML配置文件到这个目录,web app会自动找到它。


2.2.解析层次:
l1:web.xml:添加cas的servlet 
l2:cas-servlet.xml:添加propertyFileConfigurer.xml在cas servlet启动时读取
l3:propertyFileConfigurer.xml:规定配置文件路径为cas.properties
l4:cas.properties:具体的配置信息key=value
l5:jsp中,用  
<spring:theme code="byou.custom.css.file" var="customCssFile" />
<spring:message code="logo.title" />


具体如下:
(1)web.xml中配置一个servlet, name是cas
(2) 在初始化DispatcherServlet的时候,会自动加载 servlet-name+“-servlet.xml”文件。所以,cas-servlet.xml是自动加载的,不需要在配置文件进行配置。
cas-servlet.xml:
开头处添加
<import resource="spring-configuration/propertyFileConfigurer.xml"/>
ps:一开始疑惑:cas的配置文件竟然是在加载页面的时候才读取的,而不是listerer的时候就读取好的??原来web容器启动时可以加载servlet的,通过在servlet中添加load-on-startup配置启动顺序。
pps:初始化web容器时加载applicationContext用Listerner要比Servlet更好一些,而且Listerner监听应用的启动和结束,而Servlet启动要稍微延迟一些。所以spring用的是ContextLoaderListener。。但cas用了servlet

(3)WEB-INF/spring-configuration/propertyFileConfigurer.xml:规定总配置文件的地址。这样的好处是可以放war包以外的配置文件路径,而不是必须包在war包中。配置如下:
    <context:property-placeholder location="/WEB-INF/cas.properties"/> 
ps:property-placeholder的属性看 http://xiaoxuejie.iteye.com/blog/1315193
(4)cas.properties:具体的配置信息key=value,可以被cas-servlet.xml使用,也可以被其他配置所调用。
(5)配置属性的使用方式:
xml和properties中,用${key}即可读取,所以必须保证所有properties中属性名称的唯一性。
jsp中,用  
a.  <spring:theme code="byou.custom.css.file" var="customCssFile" /> —--用于定位主题资源文件,由<bean id="themeResolver" …来定位properties文件地址,并负责解析出具体配置属性(参考: http://jackandroid.iteye.com/blog/604484)
ps:theme主题的讲解:http://blog.csdn.net/wutbiao/article/details/7450281 
b.  <spring:message code="logo.title" />  —— 读取message_locale.properties
ps:从数据库中读取message的方式 :http://www.cnblogs.com/HD/p/4167331.html
0 0