spring-实现配置文件读取

spring 实现配置读取

Java 的配置读取方式一般是采用java.utils.Properties 或是apache的Configuration工具;
然而 spring 框架内置了配置文件的读取工具,支持自动注入,为了保持应用的统一性,往往利用框架功能实现配置读取;

spring实现配置读取及注入的工具类叫PropertyPlaceholderConfigurer,placeholder是占位符的意思,大致有读取并替换的意思。下面是实现步骤:

一、配置文件

将配置文件build.properties,置于classpath中,maven项目一般为src/main/resources;src/test/resources

内容如:

buildinfo.version=v1;

二、spring 引入配置

方式一:使用context:property-placeholder标签

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

 

方式二:使用bean标签

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <array>
            <value>classpath:config.properties</value>
        </array>
    </property>
</bean>

 

三、程序读取

@Compoment
public class BuildConfig{

@Value("${buildinfo.version")
private String version;

...
}

 

将BuildConfig注解为一个Component(默认是 singleton 单例),通过 applicaitonContext 加载:

BuildConfig config = application.getBean(BuildConfig.class);

 

done.

posted @ 2016-09-13 14:41  美码师  阅读(844)  评论(0编辑  收藏  举报