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

spring配置文件获取其他properties文件中的值及使用

2011-09-23 10:59 816 查看

  为避免在JAVA程序中使用Hardcode,我们经常使用一些properties文件存放一些经常变化的数据,在runtime环境下通过配置这些数据来达到灵活配置应用程序。


  1.介绍

  为避免在JAVA程序中使用Hardcode,我们经常使用一些properties文件存放一些经常变化的数据,在runtime环境下通过配置这些数据来达到灵活配置应用程序。在Spring出现以前我们通常使用resource bundle来实现对properties文件的读取,但在Spring环境下问题变得更加简单,我们只需要写非常少的代码就能实现对properties文件的随机存取。

  2.ApplicationContext.xml文件配置

  ApplicationContext是BeanFactory的扩展,它提供了BeanFactory的所有功能,ApplicationContext允许你通过完全声明的方式配置和管理Spring和Spring管理的资源,本文我提供以下实例:

  
< ?xml version="1.0" encoding="UTF-8"?>
  < !DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

  < beans>

  < bean id="configproperties"

  class="org.springframework.beans.factory.config.PropertiesFactoryBean">

  < property name="location" value="file:config.properties"/>

  < /bean>

  < bean id="propertyConfigurer"

  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

  < property name="properties" ref="configproperties"/>

  < /bean>

  < bean id="tjtaskcode" class="TJTaskCode">

  < property name="taskcode" value="${TJ.TaskCode}"/>

  < /bean>

  < /beans>

  3. Config.properties文件的配置
  本例中我提供一对简单的数据用于示范:

  #Transaction Journal Task Codes

TJ.TaskCode = 1034,1035,1037,1038,1040,1057,1058,1074

  TJ.TaskCode是键,1034,1035,1037,1038,1040,1057,1058,1074是值;

  4.Java Bean的定义

  定义Java Bean TJTaskCode.Java用于存放所需要的数值:

  
public class TJTaskCode {
  private String taskcode;

  public void setTaskcode(String taskcode) {

  this.taskcode = taskcode;

  }

  public String getTaskcode() {

  return this.taskcode;

  }

  }

  5.测试程序TestAccessProperties.java的执行
  
import org.springframework.context.ApplicationContext;
  import org.springframework.context.support.ClassPathXmlApplicationContext;

  import com.td.cc.audit.impl.TJTaskCode;

  public class TestAccessProperties {

  public static void main(String[] args) {

  ApplicationContext context;

  context = new ClassPathXmlApplicationContext("applicationContext.xml"); TJTaskCode taskcode1 = (TJTaskCode)context.getBean("tjtaskcode");

  String taskcode2 = taskcode1.getTaskcode();

  System.out.println(taskcode2);

  if (taskcode2.indexOf("1034")!=-1) //

  {

  System.out.println("Y");

  } else{

  System.out.println("N");

  }

  }

  }

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐