============================ Spring IoC依赖注入的三种方式 ============================ Spring容器在初始化过程中加载配置文件: ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); 从中读取类路径和属性信息: ... ... 再通过反射创建该类的对象。 public class ObjectTest { public static void main(String[] args) { String classPath = "cn.tedu.springioc.beans.Student"; try { Class cls = Class.forName(classPath); Object obj = cls.getDeclaredConstructor().newInstance(); Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { String fieldName = field.getName(); String setMethodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); Method setMethod = cls.getDeclaredMethod( setMethodName, field.getType()); if (fieldName.equals("number")) setMethod.invoke(obj, "1001"); else if (fieldName.equals("name")) setMethod.invoke(obj, "张飞"); else if (fieldName.equals("gender")) setMethod.invoke(obj, "男"); else if (fieldName.equals("age")) setMethod.invoke(obj, 20); else if (fieldName.equals("enrollment")) ; else if (fieldName.equals("subject")) ; } System.out.println(obj); } catch (Exception e) { e.printStackTrace(); } } } 运行测试: Student{number='1001', name='张飞', gender='男', age=20, enrollment=null, subject=null} - 上面代码所采用的依赖(属性)注入(赋值)方式称为set方法注入,最常用 - 除Set方法注入以外,Spring还支持构造器注入和接口注入,后者不常用 例程:SpringIoC