ByeService.java
package com.service; public class ByeService { public String sayBye() { return "byebye"; } }
UserService.java
package com.service; public class UserService { private String name; private ByeService byeService; public String getName() { return name; } public void setName(String name) { this.name = name; } public void setByeService(ByeService byeService) { this.byeService = byeService; } public ByeService getByeService() { return byeService; } public void sayHello() { System.out.println("hello " + name + " " + byeService.sayBye()); } }
applicationContext.xml
<bean id="userService" class="com.service.UserService" > <property name="name" value="balfish" /> <property name="byeService" ref="byeService" /></bean> <bean id="byeService" class="com.service.ByeService"></bean>
运行结果:hello balfish byebye
原理分析:
当执行 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");时,
spring容器对象被创 建,同时applicationContext.xml 中配置bean bean就会被创建(内存【HashMap/HashTable】)
xml的bean,property等被的配置被反射如下,,,,
内存(applicationContext对象引用)
id 对象
userService (0x1111) UserService【name, byeService(?-->0x2222)】
byeService (0x2222) ByeService
自己实现这个反射:dom4j + java 反射
userService = Class.forName("com.service.UserService"); //所以class是类的全路径
userService.setName("balfish"); // 反射要调用setter,必须写,且写正确
byeService = Class.forName("com.service.BybService");
userService.setByeService(byeService); //这步可以延迟一下
HashMap applicationContext = new HashMap();
applicationContext.put("userService",userService);
applicationContext.put("byeService",byeService);
ioc,DI
ioc控制反转,就是把创建对象,维护对象的关系的权利从程序中转移到spring的容器(applicationContext.xml) ,而程序本身不再维护
DI依赖注入,实际上和ioc是同一个概念,spring设计者人为DI更准确地表示spring核心技术
编程粒度变大->
指令(汇编) 语句(c) 对象(java) 组件(spring)