spring 读取配置文件属性文件读取的几种方式有什么区别

博客分类:
package com.liu.
??public class BeanFile {
?? private String beanFile = "多种方式加载Bean的配置文件";
?? public void setBeanFile(String beanFile) {
?? this.beanFile = beanF
?? public String getBeanFile() {
?? return beanF
??package com.liu.
??import java.io.FileInputS
??import java.io.FileNotFoundE
??import java.io.InputS
??import org.springframework.beans.factory.BeanF
??import org.springframework.beans.factory.support.BeanDefinitionR
??import org.springframework.beans.factory.support.DefaultListableBeanF
??import org.springframework.beans.factory.support.PropertiesBeanDefinitionR
??import org.springframework.beans.factory.xml.XmlBeanF
??import org.springframework.context.ApplicationC
??import org.springframework.context.support.ClassPathXmlApplicationC
??import org.springframework.core.io.ClassPathR
??import org.springframework.core.io.FileSystemR
??import org.springframework.core.io.InputStreamR
??import org.springframework.core.io.R
??public class MainBeanFile {
?? public static void main(String[] args) {
?? // 直接调用HelloBean
?? BeanFile bf = new BeanFile();
?? System.out.println(bf.getBeanFile());
?? * 利用XmlBeanFactory(Resource resource) 这里Resource必须是xml格式
?? * Resource包括:AbstractResource, ClassPathResource, FileSystemResource,
?? * InputStreamResource, ServletContextResource, UrlResource
?? * 利用 InputStreamResource(InputStream inputStream) 要将bean.xml放在项目根目录下,目录一定要写完整
?? InputStream is =
?? is = new FileInputStream("c:/workspace/spring/WebRoot/WEB-INF/InputStreamResource.xml");
?? } catch (FileNotFoundException e) {
?? e.printStackTrace();
?? Resource resource = new InputStreamResource(is);
?? sayHello(resource);
?? * 利用 ClassPathResource(String path) 要将bean.xml放在源文件夹(src)目录下
?? resource = new ClassPathResource("ClassPathResource.xml");
?? sayHello(resource);
?? * 利用 FileSystemResource(String path) 要将bean.xml放在项目根目录下,目录一定要写完整
?? * c:/workspace/spring/src/com/liu/test/FileSystemResource.xml
?? resource = new FileSystemResource("c:/workspace/spring/src/com/liu/test/FileSystemResource.xml");
?? sayHello(resource);
?? * 利用 Properties 要将bean.properties放在类路径--源文件夹(src)目录下
?? BeanDefinitionRegistry reg = new DefaultListableBeanFactory();
?? PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(reg);
?? reader.loadBeanDefinitions(new ClassPathResource("bean.properties"));
?? BeanFactory factory = (BeanFactory)
?? bf = (BeanFile) factory.getBean("beanFile");
?? System.out.println("利用" + bf.getBeanFile() + " 加载 Bean.properties");
?? * 利用 ApplicationContext 要将bean.xml放在类路径--源文件夹(src)目录下
?? ApplicationContext appContext = new ClassPathXmlApplicationContext(
?? "/ApplicationContext.xml");
?? bf = (BeanFile) appContext.getBean("beanFile");
?? System.out.println("利用" + bf.getBeanFile() + " 加载 Bean.xml");
?? public static void sayHello(Resource resource) {
?? BeanFactory factory = new XmlBeanFactory(resource);
?? BeanFile bf = (BeanFile) factory.getBean("beanFile");
?? System.out.println("利用 " + bf.getBeanFile() + " 加载 Bean.xml");
InputStreamResource.xml
&?xml version="1.0" encoding="GBK"?&
&!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd"&
&bean id="beanFile" class="com.liu.test.BeanFile"&
&property name="beanFile"&
&value&InputStreamResource(InputStream inputStream)&/value&
&/property&
?ClassPathResource.xml
&?xml version="1.0" encoding="GBK"?&
&!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd"&
&bean id="beanFile" class="com.liu.test.BeanFile"&
&property name="beanFile"&
&value&ClassPathResource(String path)&/value&
&/property&
FileSystemResource.xml
&?xml version="1.0" encoding="GBK"?&
&!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd"&
&bean id="beanFile" class="com.liu.test.BeanFile"&
&property name="beanFile"&
&value&FileSystemResource(String path)&/value&
&/property&
ApplicationContext.xml
&?xml version="1.0" encoding="GBK"?&
&!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd"&
&bean id="beanFile" class="com.liu.test.BeanFile"&
&property name="beanFile"&
&value&ApplicationContext&/value&
&/property&
bean.properties(Spring也可以使用属性文件来定义配置文件,bean.properties放在源文件夹(src)目录下)
??beanFile.class=com.liu.test.BeanFile
??beanFile.beanFile=properties
输出结果:(也跟log4j的配置文件有关)
??多种方式加载Bean的配置文件
??利用 InputStreamResource(InputStream inputStream) 加载 Bean.xml
??利用 ClassPathResource(String path) 加载 Bean.xml
??利用 FileSystemResource(String path) 加载 Bean.xml
?? 利用properties 加载 Bean.properties
??利用ApplicationContext 加载 Bean.xml
浏览: 224358 次
来自: 北京
感谢楼主。请受小生一拜。
一楼的同学Lucene4.* 以上的 已经改成了Numeric ...
RangeQuery在哪个包里?
有个疑问,楼主,为何初始化bits 从txt读取已有的网址是直 ...
还不如没有呢
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'spring的bean注入属性有哪几种方式_百度知道
spring的bean注入属性有哪几种方式
我有更好的答案
但是,对于系统中非Spring框架管理的类,如果需要获取Spring管理的类,或者,程序中需要动态的根据Bean的id来获取Bean实例,不可能事先为该类提供所有需要的Bean属性的setter方法,在类似这样的情况下,获取Spring框架管理的类实例的方法有多种,现在简单总结如下:方法一:在初始化时保存ApplicationContext对象代码:ApplicationContext ac = new FileSystemXmlApplicationContext(&applicationContext.xml&); ac.getBean(&beanId&);说明:这种方式适用于采用Spring框架的独立应用程序,需要程序通过配置文件手工初始化Spring的情况。方法二:通过Spring提供的工具类获取ApplicationContext对象代码:import org.springframework.web.context.support.WebApplicationContextU ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc) ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc) ac1.getBean(&beanId&); ac2.getBean(&beanId&);说明:这种方式适合于采用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象,然后在通过它获取需要的类实例。上面两个工具方式的区别是,前者在获取失败时抛出异常,后者返回null。方法三:继承自抽象类ApplicationObjectSupport说明:抽象类ApplicationObjectSupport提供getApplicationContext()方法,可以方便的获取到ApplicationContext。Spring初始化时,会通过该抽象类的setApplicationContext(ApplicationContextcontext)方法将ApplicationContext 对象注入。方法四:继承自抽象类WebApplicationObjectSupport说明:类似上面方法,调用getWebApplicationContext()获取WebApplicationContext方法五:实现接口ApplicationContextAware说明:实现该接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 对象。Spring初始化时,会通过该方法将ApplicationContext 对象注入。以上方法适合不同的情况,请根据具体情况选用相应的方法。这里值得提一点的是,系统中用到上述方法的类实际上就于Spring框架紧密耦合在一起了,因为这些类是知道它们是运行在Spring框架上的,因此,系统中,应该尽量的减少这类应用,使系统尽可能的独立于当前运行环境,尽量通过DI的方式获取需要的服务提供者。本人认为,方法五比较可行,可以设计一个工具类,专门来获取Spring中的类。减少对业务代码的侵入性。
为您推荐:
其他类似问题
spring的相关知识
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。spring属性文件读取的几种方式有什么区别? - 知乎9被浏览559分享邀请回答11 条评论分享收藏感谢收起&>&Spring配置三种数据源及从属性文件中读取DB连接四要素
Spring配置三种数据源及从属性文件中读取DB连接四要素
上传大小:167KB
Spring配置文件中注册三种数据源及从属性文件中读取DB连接四要素
综合评分:0
下载个数:
{%username%}回复{%com_username%}{%time%}\
/*点击出现回复框*/
$(".respond_btn").on("click", function (e) {
$(this).parents(".rightLi").children(".respond_box").show();
e.stopPropagation();
$(".cancel_res").on("click", function (e) {
$(this).parents(".res_b").siblings(".res_area").val("");
$(this).parents(".respond_box").hide();
e.stopPropagation();
/*删除评论*/
$(".del_comment_c").on("click", function (e) {
var id = $(e.target).attr("id");
$.getJSON('/index.php/comment/do_invalid/' + id,
function (data) {
if (data.succ == 1) {
$(e.target).parents(".conLi").remove();
alert(data.msg);
$(".res_btn").click(function (e) {
var parentWrap = $(this).parents(".respond_box"),
q = parentWrap.find(".form1").serializeArray(),
resStr = $.trim(parentWrap.find(".res_area_r").val());
console.log(q);
//var res_area_r = $.trim($(".res_area_r").val());
if (resStr == '') {
$(".res_text").css({color: "red"});
$.post("/index.php/comment/do_comment_reply/", q,
function (data) {
if (data.succ == 1) {
var $target,
evt = e || window.
$target = $(evt.target || evt.srcElement);
var $dd = $target.parents('dd');
var $wrapReply = $dd.find('.respond_box');
console.log($wrapReply);
//var mess = $(".res_area_r").val();
var mess = resS
var str = str.replace(/{%header%}/g, data.header)
.replace(/{%href%}/g, 'http://' + window.location.host + '/user/' + data.username)
.replace(/{%username%}/g, data.username)
.replace(/{%com_username%}/g, data.com_username)
.replace(/{%time%}/g, data.time)
.replace(/{%id%}/g, data.id)
.replace(/{%mess%}/g, mess);
$dd.after(str);
$(".respond_box").hide();
$(".res_area_r").val("");
$(".res_area").val("");
$wrapReply.hide();
alert(data.msg);
}, "json");
/*删除回复*/
$(".rightLi").on("click", '.del_comment_r', function (e) {
var id = $(e.target).attr("id");
$.getJSON('/index.php/comment/do_comment_del/' + id,
function (data) {
if (data.succ == 1) {
$(e.target).parent().parent().parent().parent().parent().remove();
$(e.target).parents('.res_list').remove()
alert(data.msg);
//填充回复
function KeyP(v) {
var parentWrap = $(v).parents(".respond_box");
parentWrap.find(".res_area_r").val($.trim(parentWrap.find(".res_area").val()));
评论共有0条
VIP会员动态
CSDN下载频道资源及相关规则调整公告V11.10
下载频道用户反馈专区
下载频道积分规则调整V1710.18
spring mvc+mybatis+mysql+maven+bootstrap 整合实现增删查改简单实例.zip
资源所需积分/C币
当前拥有积分
当前拥有C币
输入下载码
为了良好体验,不建议使用迅雷下载
Spring配置三种数据源及从属性文件中读取DB连接四要素
会员到期时间:
剩余下载个数:
剩余积分:0
为了良好体验,不建议使用迅雷下载
积分不足!
资源所需积分/C币
当前拥有积分
您可以选择
程序员的必选
绿色安全资源
资源所需积分/C币
当前拥有积分
当前拥有C币
为了良好体验,不建议使用迅雷下载
资源所需积分/C币
当前拥有积分
当前拥有C币
为了良好体验,不建议使用迅雷下载
资源所需积分/C币
当前拥有积分
当前拥有C币
您的积分不足,将扣除 10 C币
为了良好体验,不建议使用迅雷下载
无法举报自己的资源
你当前的下载分为234。
你还不是VIP会员
开通VIP会员权限,免积分下载
你下载资源过于频繁,请输入验证码
您因违反CSDN下载频道规则而被锁定帐户,如有疑问,请联络:!
若举报审核通过,可返还被扣除的积分
被举报人:
举报的资源分:
请选择类型
资源无法下载 ( 404页面、下载失败、资源本身问题)
资源无法使用 (文件损坏、内容缺失、题文不符)
侵犯版权资源 (侵犯公司或个人版权)
虚假资源 (恶意欺诈、刷分资源)
含色情、危害国家安全内容
含广告、木马病毒资源
*详细原因:
Spring配置三种数据源及从属性文件中读取DB连接四要素点击这里,将文章分享到自己的动态
SpringBoot项目实战(8):四种读取properties文件的方式
在项目开发中经常会用到配置文件,配置文件的存在解决了很大一份重复的工作。今天就分享四种在Springboot中获取配置文件的方式。
注:前三种测试配置文件为springboot默认的application.properties文件
#######################方式一#########################
com.zyd.type3=Springboot - @ConfigurationProperties
com.zyd.title3=使用@ConfigurationProperties获取配置文件
com.zyd.login[username]=zhangdeshuai
com.zyd.login[password]=zhenshuai
com.zyd.login[callback]=http://www.flyat.cc
com.zyd.urls[0]=http://ztool.cc
com.zyd.urls[1]=http://ztool.cc/format/js
com.zyd.urls[2]=http://ztool.cc/str2image
com.zyd.urls[3]=http://ztool.cc/json2Entity
com.zyd.urls[4]=http://ztool.cc/ua
#######################方式二#########################
com.zyd.type=Springboot - @Value
com.zyd.title=使用@Value获取配置文件
#######################方式三#########################
com.zyd.type2=Springboot - Environment
com.zyd.title2=使用Environment获取配置文件
一、@ConfigurationProperties方式
自定义配置类:PropertiesConfig.java
package com.zyd.property.
import java.io.UnsupportedEncodingE
import java.util.ArrayL
import java.util.HashM
import java.util.L
import java.util.M
import org.springframework.boot.context.properties.ConfigurationP
//import org.springframework.context.annotation.PropertyS
import org.springframework.stereotype.C
* 对应上方配置文件中的第一段配置
* @author &a href="mailto:yadong."&yadong.zhang&/a&
* @date 日 下午4:34:18
* @version V1.0
* @since JDK : 1.7
@Component
@ConfigurationProperties(prefix = "com.zyd")
// PropertySource默认取application.properties
// @PropertySource(value = "config.properties")
public class PropertiesConfig {
public String type3;
public String title3;
public Map&String, String& login = new HashMap&String, String&();
public List&String& urls = new ArrayList&&();
public String getType3() {
return type3;
public void setType3(String type3) {
this.type3 = type3;
public String getTitle3() {
return new String(title3.getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return title3;
public void setTitle3(String title3) {
this.title3 = title3;
public Map&String, String& getLogin() {
public void setLogin(Map&String, String& login) {
this.login =
public List&String& getUrls() {
public void setUrls(List&String& urls) {
this.urls =
程序启动类:Applaction.java
package com.zyd.
import java.io.UnsupportedEncodingE
import java.util.HashM
import java.util.M
import org.springframework.beans.factory.annotation.A
import org.springframework.boot.SpringA
import org.springframework.boot.autoconfigure.SpringBootA
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RestC
import com.zyd.property.config.PropertiesC
* @author &a href="mailto:yadong."&yadong.zhang&/a&
* @date 日 下午3:49:30
* @version V1.0
* @since JDK : 1.7
@SpringBootApplication
@RestController
public class Applaction {
@Autowired
private PropertiesConfig propertiesC
* 第一种方式:使用`@ConfigurationProperties`注解将配置文件属性注入到配置对象类中
* @author zyd
* @throws UnsupportedEncodingException
* @since JDK 1.7
@RequestMapping("/config")
public Map&String, Object& configurationProperties() {
Map&String, Object& map = new HashMap&String, Object&();
map.put("type", propertiesConfig.getType3());
map.put("title", propertiesConfig.getTitle3());
map.put("login", propertiesConfig.getLogin());
map.put("urls", propertiesConfig.getUrls());
public static void main(String[] args) throws Exception {
SpringApplication application = new SpringApplication(Applaction.class);
application.run(args);
访问结果:
{"title":"使用@ConfigurationProperties获取配置文件","urls":["http://ztool.cc","http://ztool.cc/format/js","http://ztool.cc/str2image","http://ztool.cc/json2Entity","http://ztool.cc/ua"],"login":{"username":"zhangdeshuai","callback":"http://www.flyat.cc","password":"zhenshuai"},"type":"Springboot - @ConfigurationProperties"}
二、使用@Value注解方式
程序启动类:Applaction.java
package com.zyd.
import java.io.UnsupportedEncodingE
import java.util.HashM
import java.util.M
import org.springframework.beans.factory.annotation.V
import org.springframework.boot.SpringA
import org.springframework.boot.autoconfigure.SpringBootA
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RestC
* @author &a href="mailto:yadong."&yadong.zhang&/a&
* @date 日 下午3:49:30
* @version V1.0
* @since JDK : 1.7
@SpringBootApplication
@RestController
public class Applaction {
@Value("${com.zyd.type}")
@Value("${com.zyd.title}")
* 第二种方式:使用`@Value("${propertyName}")`注解
* @author zyd
* @throws UnsupportedEncodingException
* @since JDK 1.7
@RequestMapping("/value")
public Map&String, Object& value() throws UnsupportedEncodingException {
Map&String, Object& map = new HashMap&String, Object&();
map.put("type", type);
// *.properties文件中的中文默认以ISO-8859-1方式编码,因此需要对中文内容进行重新编码
map.put("title", new String(title.getBytes("ISO-8859-1"), "UTF-8"));
public static void main(String[] args) throws Exception {
SpringApplication application = new SpringApplication(Applaction.class);
application.run(args);
访问结果:
{"title":"使用@Value获取配置文件","type":"Springboot - @Value"}
三、使用Environment
程序启动类:Applaction.java
package com.zyd.
import java.io.UnsupportedEncodingE
import java.util.HashM
import java.util.M
import org.springframework.beans.factory.annotation.A
import org.springframework.boot.SpringA
import org.springframework.boot.autoconfigure.SpringBootA
import org.springframework.core.env.E
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RestC
* @author &a href="mailto:yadong."&yadong.zhang&/a&
* @date 日 下午3:49:30
* @version V1.0
* @since JDK : 1.7
@SpringBootApplication
@RestController
public class Applaction {
@Autowired
* 第三种方式:使用`Environment`
* @author zyd
* @throws UnsupportedEncodingException
* @since JDK 1.7
@RequestMapping("/env")
public Map&String, Object& env() throws UnsupportedEncodingException {
Map&String, Object& map = new HashMap&String, Object&();
map.put("type", env.getProperty("com.zyd.type2"));
map.put("title", new String(env.getProperty("com.zyd.title2").getBytes("ISO-8859-1"), "UTF-8"));
public static void main(String[] args) throws Exception {
SpringApplication application = new SpringApplication(Applaction.class);
application.run(args);
访问结果:
{"title":"使用Environment获取配置文件","type":"Springboot - Environment"}
四、使用PropertiesLoaderUtils
app-config.properties
#### 通过注册监听器(`Listeners`) + `PropertiesLoaderUtils`的方式
com.zyd.type=Springboot - Listeners
com.zyd.title=使用Listeners + PropertiesLoaderUtils获取配置文件
com.zyd.name=zyd
com.zyd.address=Beijing
com.zyd.company=in
PropertiesListener.java 用来初始化加载配置文件
package com.zyd.property.
import org.springframework.boot.context.event.ApplicationStartedE
import org.springframework.context.ApplicationL
import com.zyd.property.config.PropertiesListenerC
* 配置文件监听器,用来加载自定义配置文件
* @author &a href="mailto:yadong."&yadong.zhang&/a&
* @date 日 下午3:38:25
* @version V1.0
* @since JDK : 1.7
public class PropertiesListener implements ApplicationListener&ApplicationStartedEvent& {
private String propertyFileN
public PropertiesListener(String propertyFileName) {
this.propertyFileName = propertyFileN
public void onApplicationEvent(ApplicationStartedEvent event) {
PropertiesListenerConfig.loadAllProperties(propertyFileName);
PropertiesListenerConfig.java 加载配置文件内容
package com.zyd.property.
import java.io.IOE
import java.io.UnsupportedEncodingE
import java.util.HashM
import java.util.M
import java.util.P
import org.springframework.beans.BeansE
import org.springframework.core.io.support.PropertiesLoaderU
* 第四种方式:PropertiesLoaderUtils
* @author &a href="mailto:yadong."&yadong.zhang&/a&
* @date 日 下午3:32:37
* @version V1.0
* @since JDK : 1.7
public class PropertiesListenerConfig {
public static Map&String, String& propertiesMap = new HashMap&&();
private static void processProperties(Properties props) throws BeansException {
propertiesMap = new HashMap&String, String&();
for (Object key : props.keySet()) {
String keyStr = key.toString();
// PropertiesLoaderUtils的默认编码是ISO-8859-1,在这里转码一下
propertiesMap.put(keyStr, new String(props.getProperty(keyStr).getBytes("ISO-8859-1"), "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (java.lang.Exception e) {
e.printStackTrace();
public static void loadAllProperties(String propertyFileName) {
Properties properties = PropertiesLoaderUtils.loadAllProperties(propertyFileName);
processProperties(properties);
} catch (IOException e) {
e.printStackTrace();
public static String getProperty(String name) {
return propertiesMap.get(name).toString();
public static Map&String, String& getAllProperty() {
return propertiesM
Applaction.java 启动类
package com.zyd.
import java.io.UnsupportedEncodingE
import java.util.HashM
import java.util.M
import org.springframework.boot.SpringA
import org.springframework.boot.autoconfigure.SpringBootA
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RestC
import com.zyd.property.config.PropertiesListenerC
import com.zyd.property.listener.PropertiesL
* @author &a href="mailto:yadong."&yadong.zhang&/a&
* @date 日 下午3:49:30
* @version V1.0
* @since JDK : 1.7
@SpringBootApplication
@RestController
public class Applaction {
* 第四种方式:通过注册监听器(`Listeners`) + `PropertiesLoaderUtils`的方式
* @author zyd
* @throws UnsupportedEncodingException
* @since JDK 1.7
@RequestMapping("/listener")
public Map&String, Object& listener() {
Map&String, Object& map = new HashMap&String, Object&();
map.putAll(PropertiesListenerConfig.getAllProperty());
public static void main(String[] args) throws Exception {
SpringApplication application = new SpringApplication(Applaction.class);
// 第四种方式:注册监听器
application.addListeners(new PropertiesListener("app-config.properties"));
application.run(args);
访问结果:
{"com.zyd.name":"zyd","com.zyd.address":"Beijing","com.zyd.title":"使用Listeners + PropertiesLoaderUtils获取配置文件","com.zyd.type":"Springboot - Listeners","com.zyd.company":"in"}
详细代码请移步:
我的其他相关文章
若觉得本文不错,就分享一下吧!
评论加载中...
看过此文的用户,还看了以下文章
正在加载中
JAVA开发工程师
作者相关文章

我要回帖

更多关于 spring 读取属性文件 的文章

 

随机推荐