在Spring环境下如何存取properties文件中的数值

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

1.介绍为避免在JAVA程序中使用Hardcode,我们经常使用一些properties文件存放一些经常变化的数据,在runtime环境下通过配置这些数据来达到灵活配置应用程序。在Spring出现以前我们通常使用resourcebundle来实现对properties文件的读取,但在Spring环境下问题变得更加简单,我们只需要写非常少的代码就能实现对properties文件的随机存取。2.ApplicationContext.xml文件配置ApplicationContext是BeanFactory的扩展,它提供了BeanFactory的所有功能,ApplicationContext允许你通过完全声明的方式配置和管理Spring和Spring管理的资源,本文我提供以下实例:?xmlversion=1.0encoding=UTF-8?!DOCTYPEbeansPUBLIC-//SPRING//DTDBEAN//EN=configpropertiesclass=org.springframework.beans.factory.config.PropertiesFactoryBeanpropertyname=locationvalue=file:config.properties//beanbeanid=propertyConfigurerclass=org.springframework.beans.factory.config.PropertyPlaceholderConfigurerpropertyname=propertiesref=configproperties//beanbeanid=tjtaskcodeclass=TJTaskCodepropertyname=taskcodevalue=${TJ.TaskCode}//bean/beans3.Config.properties文件的配置本例中我提供一对简单的数据用于示范:#TransactionJournalTaskCodesTJ.TaskCode=1034,1035,1037,1038,1040,1057,1058,1074TJ.TaskCode是键,1034,1035,1037,1038,1040,1057,1058,1074是值;4.JavaBean的定义定义JavaBeanTJTaskCode.Java用于存放所需要的数值:publicclassTJTaskCode{privateStringtaskcode;publicvoidsetTaskcode(Stringtaskcode){this.taskcode=taskcode;}publicStringgetTaskcode(){returnthis.taskcode;}}5.测试程序TestAccessProperties.java的执行importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importcom.td.cc.audit.impl.TJTaskCode;publicclassTestAccessProperties{publicstaticvoidmain(String[]args){ApplicationContextcontext;context=newClassPathXmlApplicationContext(applicationContext.xml);TJTaskCodetaskcode1=(TJTaskCode)context.getBean(tjtaskcode);Stringtaskcode2=taskcode1.getTaskcode();System.out.println(taskcode2);if(taskcode2.indexOf(1034)!=-1){System.out.println(Y);}else{System.out.println(N);}}}

1 / 2
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功