您的位置:首页 > 编程语言 > Java开发

Spring使用程序方式读取properties文件

2014-03-21 10:44 344 查看
Spring使用程序方式读取properties文件

在spring中可以通过下面的方式将配置文件中的项注入到配置中
      
<bean
       
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
       
<propertyname="systemPropertiesModeName"value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
       
<propertyname="ignoreResourceNotFound"value="true"/>
       
<propertyname="locations">
           
<list>
               
<!-- standardconfig -->
               
<value>classpath*:application.properties</value>
           
</list>
       
</property>
    </bean>
 
    <beanid="cacheManager"class="cn.outofmemory.util.MemCacheManager"init-method="init">
       
<propertyname="nodeList" 
value="${memcache.nodelist}"/>
       
<propertyname="initConn"value="${memcache.initConn}"/>
       
<propertyname="minConn"value="${memcache.minConn}"/>
       
<propertyname="maxConn"value="${memcache.maxConn}"/>
       
<propertyname="maxIdle"value="${memcache.maxIdle}"/>
       
<propertyname="maintSleep"value="${memcache.maintSleep}"/>
    </bean>
但是这样的注入没有办法通过程序来访问properties文件中的内容,spring还提供了org.springframework.core.io.support.PropertiesLoaderUtils类可以方便的载入配置文件,如下两行代码:
Resource resource =
newClassPathResource("/application.properties");
Properties props =
PropertiesLoaderUtils.loadProperties(resource);
需要引用下面的类:
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: