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

很多时候需要将配置信息从程序中剥离粗来,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());
    }
}

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

posted @ 2015-09-14 16:17  javaadu  阅读(513)  评论(0编辑  收藏  举报