Moveable
package com.bjsxt.spring.factory;
public interface Moveable {
void run();
}
Car
package com.bjsxt.spring.factory;
public class Car implements Moveable {
public void run() {
System.out.println("冒着烟奔跑中car.......");
}
}
Train
package com.bjsxt.spring.factory;
public class Train implements Moveable {
@Override
public void run() {
System.out.println("小火车呜呜呜");
}
}
spring.properties 这里用配置文件,所以不需要更改代码,只需要更改, Car - Train 什么的就好!
VehicleType=com.bjsxt.spring.factory.Car
Test
package com.bjsxt.spring.factory;
import java.io.IOException;
import java.util.Properties;
public class Test {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.load(Test.class.getClassLoader().getResourceAsStream("com/bjsxt/spring/factory/spring.properties"));
String vehicleTypeName = props.getProperty("VehicleType");
System.out.println(vehicleTypeName);
Object o = Class.forName(vehicleTypeName).newInstance();
Moveable m = (Moveable)o;
m.run();
}
}
---------Spring3.0 读取 比较---------------------- 将所需 jar包 加入 build path----
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="v" class="com.bjsxt.spring.factory.Car">
</bean>
<!-- v=com.bjsxt.spring.factory.Car -->
</beans>
Test
package com.bjsxt.spring.factory;
import java.io.IOException;
import java.util.Properties;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws Exception {
BeanFactory f = new ClassPathXmlApplicationContext("applicationContext.xml");
Object o = f.getBean("v");
Moveable m = (Moveable)o;
m.run();
}
}