如何配置Spring bean容器来加载Java属性文件? [英] How do you configure a Spring bean container to load a Java property file?

查看:179
本文介绍了如何配置Spring bean容器来加载Java属性文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何配置Spring bean容器(或应用程序上下文)来加载Java属性文件?

How do you configure a Spring bean container (or application context) to load a Java property file?

JavaWorld 文章 智能加载属性 说明如何使用标准Java库中的以下资源处理方法之一从类路径加载属性文件:

JavaWorld article Smartly Load Your Properties explains how to load property files from the classpath using one of the following resource processing methods in the standard Java library:

ClassLoader.getResourceAsStream ("some/pkg/resource.properties");
Class.getResourceAsStream ("/some/pkg/resource.properties");
ResourceBundle.getBundle ("some.pkg.resource");

如何使用Spring bean容器执行相同操作?

How can you do the same using a Spring bean container?

推荐答案

Spring Framework Reference Documentation(2.5.x)提供了两个如何将属性文件加载到bean容器中的示例,一个在版本发布之前2.5和使用版本2.5中引入的< util:properties /> 函数的更简洁的方法:

The Spring Framework Reference Documentation (2.5.x) gives two examples of how to load a property file into a bean container, one before the release of version 2.5 and a more concise way using the <util:properties/> function that was introduced in version 2.5:

2.5版之前:

<!-- creates a java.util.Properties instance with values loaded from the supplied location -->
<bean id="jdbcConfiguration" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="location" value="classpath:com/foo/jdbc-production.properties"/>
</bean>

版本2.5之后:

<!-- creates a java.util.Properties instance with values loaded from the supplied location -->
<util:properties id="jdbcConfiguration" location="classpath:com/foo/jdbc-production.properties"/>

请注意,为了使用< util:properties /> ,您必须在Spring XML配置文件顶部的前导码中声明 util 命名空间和架构位置:

Note that in order to use <util:properties/>, you must declare the util namespace and schema location in the preamble at the top of your Spring XML configuration file:

<?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:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">

<!-- <bean/> definitions here -->

</beans>

这篇关于如何配置Spring bean容器来加载Java属性文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆