First, Target: Read the properties file, get the class name to generate the object
Second, class
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: "=" cannot have spaces on either side
Vechiletype=com.tong.spring.factory.car
4.test.java
public class Test {@org. junit.testpublic void Test () {//reads the properties file, obtains the class name to generate the object properties Pros = new properties (); try {/ /1. Read the class name to instantiate Pros.load (Test.class.getClassLoader (). getResourceAsStream ("com/tong/spring/factory/ Spring.properties ")); String Vechiletype = Pros.getproperty ("Vechiletype");//2. Use reflection to load classes and instantiate classes with newinstance () object o = Class.forName ( Vechiletype). newinstance (); Movable m = (movable) o;m.run ();} catch (Exception e) {e.printstacktrace ();}}}
5. Operation Result:
6. If you change to spring to read the XML file, when spring is configured, add 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 beans definitions go here--></ Beans>
7.test.java change to the following
public class Test {@org. junit.testpublic void Test () {Beanfactory factory = new Classpathxmlapplicationcontext (" Applicationcontext.xml "); Object o = Factory.getbean (" vehicle "); Movable m = (movable) o;m.run ();}}
Java Read the properties file