Spring中加载配置文件

 使用springorg.springframework.beans.factory.config.PropertyPlaceholderConfigurer类加载Properties配置文件,通过源码可以知道,默认加载的是classpath下的文件,配置如下:

<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

  <property name="location">

     <value>classpath:config/init.properties</value>

  </property>

 </bean>

 

如果有多个配置文件加载,则:

<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

  <property name="locations">

   <list>
     <value>classpath:config/init.properties</value>

    <value>classpath:config/init.properties</value>

   </list>

  </property>

 </bean>

 

这样spring就能够加载properties文件了。

配置文件位于外部目录

  但是对于外部目录的配置文件,使用org.springframework.beans.factory.config.PropertyPlaceholderConfigurer也是可以加载的,不过要修改他的路径配置方式,如下:

<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

  <property name="locations">

   <list>

     <value>file:${user.dir}/config/init.properties</value>

     <value>file:${user.dir}/config/init2.properties</value>

   </list>

  </property>

 </bean>

 

这样就可以成功加载外部目录的配置文件了,${user.dir}是系统变量,指用户当前目录所在。

代码中加载配置文件

  应该某些需求,配置文件得从java代码是加载,这里我就说一样代码中加载外部目录的配置文件的方式,加载classpath目录下的配置文件这里就不再多说了,相

信网上有太多较好的简答。如下代码:

private static final Properties sysConfig = new Properties();

 

    static {

        try {

            InputStream iStream = new FileInputStream(new File("config", "shellConfig.properties"));

            sysConfig.load(iStream);

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

    

    public static String getPropertyValue(String key){

        return sysConfig.getProperty(key);

    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值