通过Properties类加反射达到配置文件信息的读取的实现,单方面实现,仅供学习参考,实际使用还是按照实际生产:
假设代码包package已经已经new了,在下面创建一个文件,右键--->new--->File--->name为spring.properties
内容为:
spring.properties --->>>>
VechicleType=com.*******.Train
------------------------------------------------
以下为参考代码:
public interface BeanFactory {
Object getBean(String id);
}
---------------------------------------------------------------------
public class Car implements Moveable {
public void run() {
System.out.println("冒着烟奔跑中car...");
}
}
---------------------------------------------------------------------
public interface Moveable {
void run();
}
---------------------------------------------------------------------
public class Test {
public static void main(String[] args) throws Exception {
Properties pros = new Properties();
pros.load(Test.class.getClassLoader().getResourceAsStream("com/wch/factory/springFactory/spring.properties"));//站在JVM上,每个java类load到内存后都会被当场一哥class对象
String vehicleTypeName = pros.getProperty("VechicleType");//as a key
System.out.println(vehicleTypeName);
//We won't create new instance here!
Object obj = Class.forName(vehicleTypeName).newInstance(); //路径里面的类load到内存,但是Class装载到内存是尚且没有产生实例,还需要实例化new instance.
Moveable m = (Moveable)obj;
m.run();
}
}
---------------------------------------------------------------------
public class Train implements Moveable {
@Override
public void run() {
System.out.println("小火车呜呜呜...");
}
}
---------------------------------------------------------------------