一、目标:读取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();
}
}