spring和springmvc的配置文件整合

spring和springmvc的配置文件整合

原创  2016年05月11日 16:57:08

spring和springmvc如何集成这里就不多做介绍了,本人在集成过程中,发现一个很严重的“小问题”。

在springmvc的controller中,是可以@Autowire任意的bean的,这是因为他们的容器是“共享的”,但是某些属性,例如jdbc的配置属性,在controller中是无法@到的,根本原因还是springmvc和spring他们的上下文是伪共享。

根据UCM的思想,任意属性在任何地方都是可以被@到的,那如何在springmvc中去@某个配置属性呢。

 

先看方法一:

就是在springmvc和spring的xml配置文件中都把属性文件引入一遍,这样springmvc和spirng就是各用个的,如果后期有修改,两个地方都需要修改。

 

springcontext.xml中加入:

[html]  view plain  copy
  1. <context:property-placeholderlocationcontext:property-placeholderlocation="classpath:/config/jdbc.properties"    />  

springmvc.xml中加入:

[html]  view plain  copy
  1. <context:property-placeholderlocationcontext:property-placeholderlocation="classpath:/config/jdbc.properties"    />  

在代码中,可以这样@需要的属性配置

[java]  view plain  copy
  1. @Value("${jdbc.username}")  
  2. private Stringusername;  

 

此法虽好,但是同样的代码写两份,总是不够完美。

其实若想只加载一份就在两个地方使用,那就需要将配置文件的加载分成两步来操作。在spring中,PropertiesFactoryBean可以将多个properties文件加载为一个bean(本质上时一个hashtable),而< context:property-placeholder/> 又支持引用某个配置bean,因此可以采取如下方法来加载properties文件。

且看方法二:

在springcontext.xml中加入

[html]  view plain  copy
  1. <span style="font-family: 宋体; font-size: 10.5pt; background-color: rgb(255, 255, 255);"></span><pre name="code" class="html"><!-- 配置文件加载器 -->  
  2. <beanidbeanid="applicationProperties"  
  3. class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
  4. <propertynamepropertyname="ignoreResourceNotFound" value="true" />  
  5. <propertynamepropertyname="locations">  
  6. <list>  
  7. <value>classpath:/config-base/*.properties</value>  
  8. <value>classpath:/config/*.properties</value>  
  9. </list>  
  10. </property>  
  11. </bean>  
  12.   
  13. <!-- 引用配置文件加载器,并使支持${}的形式 -->  
  14. <context:property-placeholderproperties-refcontext:property-placeholderproperties-ref="applicationProperties"  />  

springmvc.xml中加入:

[html]  view plain  copy
  1. <!-- 引用配置文件加载器,并使支持${}的形式 -->  
  2. <context:property-placeholderproperties-refcontext:property-placeholderproperties-ref="applicationProperties"  />  

 

这样就可以在任何controller或service中@我们需要的属性了。 

注:

1.       <context:property-placeholder />的实现类是PropertyPlaceholderConfigurer,而且只有配置了<context:property-placeholder />或PropertyPlaceholderConfigurer这个类,spring才能支持@Value("${}")这种方式注入属性

2.spring或springmvc上下文中,只允许存在一个<context:property-placeholder />,配置多个的话,只有第一个或生效(当然可以通过order更改加载顺序,但最终还是只有一个生效),因此若想加载多个配置文件的话,可以使用通配符*等或者用逗号隔开多个路径,例如这样配置

[html]  view plain  copy
  1. <util:properties id="jdbcProperties"location="classpath:/config/*.properties,classpath:/config2/*.properties" />  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值