码迷,mamicode.com
首页 > 编程语言 > 详细

Java 读取Properties文件

时间:2015-06-18 21:50:59      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

一、目标:读取properties文件,获得类名来生成对象

二、类

1.Movable.java

public interface Movable {
	void run();
}

  

2.Car.java

public class Car implements Movable {

	public void run() {
		System.out.println("Car running...............");
	}
	
}

  

3.spring.properties

PS:"="两边不能有空格

vechileType=com.tong.spring.factory.Car

  

4.Test.java

public class Test {
	
	@org.junit.Test
	public void test() {
		
		//读取properties文件,获得类名来生成对象
		Properties pros = new Properties();
		
		try {
			//1.读取要实例化的类名
			pros.load(Test.class.getClassLoader().getResourceAsStream("com/tong/spring/factory/spring.properties"));
			String vechileType = pros.getProperty("vechileType");
			
			//2.利用反射装载类及用newInstance()实例化类
			Object o = Class.forName(vechileType).newInstance();
			Movable m = (Movable)o;
			m.run();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

  

5.运行结果:

技术分享

 

 

6.若改成spring读取xml文件,则spring配置好后,增加applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

  <bean id="vehicle" class="com.tong.spring.factory.Car">
  </bean>

  <!-- more bean definitions go here -->

</beans>

  

7.Test.java改为如下

public class Test {
	
	@org.junit.Test
	public void test() {
		
		BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
		Object o = factory.getBean("vehicle");
		Movable m = (Movable)o;
		m.run();
	}
}

  

 

Java 读取Properties文件

标签:

原文地址:http://www.cnblogs.com/shamgod/p/4586971.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!