Spring中获取外部配置文件中的属性值

本文介绍如何使用Spring框架的@Value注解和<context:property-placeholder>来从配置文件中读取属性值。通过一个具体示例展示了配置文件的创建、XML文件中的配置以及Java类中的使用。

很多时候需要将配置信息从程序中剥离粗来,Spring现在提供的方法是通过@Value注解和<context:placeholder>来获取配置文件中的配置信息。这里给出一个简单的例子。

首先在resources文件夹下简历配置文件spring.biz.properties,文件内容为:

dataId=test
versionId=1.0.1.daily

然后在xml文件中读入该属性值,spring-config.xml文件的内容如下:

<context:property-placeholder location="classpath:spirng.biz.properties"/>

第三步是定义需要这些属性的类,要使用注解必须在xml文件中打开注解驱动,代码为:<context:annotation-config/>。@Value注解中使用${key}取出key对应的value。TestConfig.java的内容为如下。

package com.javadu.core;

import org.springframework.beans.factory.annotation.Value;

/**
 * Created by duqi on 15/9/14.
 */
public class TestConfig {
    @Value("${dataId}")
    private String dataId;
    @Value("${versionId}")
    private String versionId;

    private String other;

    public void setOther(String other){
        this.other = other;
    }

    public String getDataId(){
        return dataId;
    }

    public String getVersionId(){
        return versionId;
    }
}

在xml文件中定义TestConfig对应的bean,完整的spring-config.xml文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

       <context:annotation-config/>
       <context:property-placeholder location="classpath:spirng.biz.properties"/>

       <bean id="configBean" class="com.javadu.core.TestConfig">
              <property name="other" value="otherother"/>
       </bean>
</beans>

最后,在App.java类中:启动IoC容器,获取TestBean的实例,调用其开放的接口,代码如下:

package com.javadu.common;


import com.javadu.core.TestConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created by duqi on 15/9/8.
 */
public class App {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        TestConfig configBean = (TestConfig)context.getBean("configBean");
        System.out.println(configBean.getDataId());
        System.out.println(configBean.getVersionId());
    }
}

最后的运行结果如下:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值