天天看点

spring-实现配置文件读取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.

spring-实现配置文件读取spring 实现配置读取

作者:

zale

出处:

http://www.cnblogs.com/littleatp/

, 如果喜欢我的文章,请

关注我的公众号

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出

原文链接

 如有问题, 可留言咨询.