第一步:编写两个简单的业务类
Service1.java
package com.xuzhiwen.service; public class Service1 { public void doService1(){ System.out.println("业务方法一"); } }
Service2.java
package com.xuzhiwen.service; public class Service2 { public void doService2(){ System.out.println("业务方法二"); } }
第二步:新增配置文件
spring.txt
class=com.xuzhiwen.service.Service2
method=doService2
第三步:编写测试类
TestService.java
package com.xuzhiwen.service; import java.io.File; import java.io.FileInputStream; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.Properties; public class TestService { public static void main(String[] args) throws Exception { String temp = new File("src/com/xuzhiwen/service/spring.txt").getAbsolutePath(); System.out.println(temp); File file = new File(temp); Properties pro = new Properties(); pro.load(new FileInputStream(file)); //获取配置文件类名 String className = pro.getProperty("class"); //获取配置文件方法名 String methodName = pro.getProperty("method"); System.out.println(className); System.out.println(methodName); //根据类全名获取类的对象 Class<?> cc = Class.forName(className); //根据方法名获取方法对象 Method mm = cc.getMethod(methodName); //获取构造器 Constructor<?> contor = cc.getConstructor(); //根据构造器实例化对象 Object obj = contor.newInstance(); mm.invoke(obj); } }
第四步:运行程序,结果如下
第五步: 文件结构树