spring 中util:properties和context:property-placeholder区别和@Value取不到值情况

一、util:properties的用法

需要在xml顶部加入:

在beans描述头的 xmlns 里加入:

xmlns:util="http://www.springframework.org/schema/util"

在 xsi:schemaLocation 里追加

http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd

<util:properties id=“settings” location=“classpath:configure.properties”></util:properties>

它是以声明bean方式来使用,创建了一个bean,下面使用的时候通过SpEL表达式#{}获取bean的属性。

<util:properties id="config" location="classpath:db.properties" />
<!-- 配置连接池 -->
<bean id="ds" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="#{config.driver}" />
<property name="url" value="#{config.url}" />
<property name="username" value="#{config.username}" />
<property name="password" value="#{config.password}" />
</bean>

如果在类中

@Value("#{config.username}")
private string username;

也可以

 @Resource
	public Properties config;
	private  static String username=config.getProperty("config.username");

二、context:property-placeholder用法

需要在xml顶部加入:

在beans描述头的 xmlns 里加入:

xmlns:context="http://www.springframework.org/schema/context"

在 xsi:schemaLocation 里追加

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd

然后在beans内容体里

<context:property-placeholder location=“classpath:configure.properties” />
将配置文件加载至spring上下文中,然后通过${}取得值

<context:property-placeholder location="classpath:general.properties"/>
<!-- 配置Druid连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <!-- 基本属性 driverClassName、url、user、password -->
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>

如果在类中

@Value("${config.username}")
private string username;

三、@Value取不到值原因

1、当SpringMVC与Spring整合使用的时候,在Controller中无法获取@Value对应的值
产生原因: 只在applicationContext中添加了扫描,没有在SpringMVC对应的配置文件中扫描。

applicationContext加载的是父容器,,父容器在项目启动的时候就被加载了。SpringMVC对应的配置文件加载的是子容器,子容器可以访问父容器的对象,但是不能访问加载的配置文件。所以,如果想在SpringMVC中使用加载的配置文件,需要在SpringMVC对应的配置文件中添加相应的配置即可。
2、在service或者dao层无法获取@Value的数值
可能情况:有多个applicationContext.xml文件,里面有多个context:property-placeholder,在web容器启动的时候同时加载了这些配置文件,这时候只会有一个配置文件中的context:property-placeholder会被加载,其他的不会被加载。
可以用下面的方法
<context:property-placeholder location="classpath:resource/.properties"/>
这样,将所有需要加载的properties放在一个目录之下,通过
.properties就可以加载所有的properties文件。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值