ApplicationContext.xml文件配置的两种方式

来源:互联网 发布:高一优化方案英语答案 编辑:程序博客网 时间:2024/06/14 23:40

今天无意中发现在ApplicationContext.xml文件中获取外置文件的参数采用的是context,而不是 spring,就想着在spring的IOC中是不是也有一种方式可以解决这个问题,经过查找,发现是可以的通过某些内置的类,就可以实现:

废话少说:

第一种:

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="
  http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-3.0.xsd
  ">

<context:property-placeholder location="classpath:jdbc.properties" />

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
 
  destroy-method="close">
  <property name="driverClass" value="${jdbc.driverClass}" />
  <property name="jdbcUrl" value="${jdbc.url}" />
  <property name="user" value="${jdbc.username}" />

     。。。。。。。。。。
   </bean>

 

第二种通过IOC/DI形式注入(此处为转载):

  < ?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>

  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是值;

  .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;

  }

  }

 

******************

 

测试程序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");

  }

  }

  }