利用Java代码实现Spring内部IOC实现原理 就三步
第一步:解析XML
第二步:获取每个Bean的Class
第三步:利用反射对Bean的私有属性赋值
public class ClassPathXmlApplicationContext {
private String xmlPath;
public ClassPathXmlApplicationContext(String xmlPath) {
this.xmlPath = xmlPath;
}
public Object getBean(String beanId) throws DocumentException, ClassNotFoundException, NoSuchFieldException,
SecurityException, IllegalArgumentException, IllegalAccessException, InstantiationException {
// spring 加载过程 或者spring ioc实现原理
// 1.读取xml配置文件
// 获取xml解析器
SAXReader saxReader = new SAXReader();
// this.getClass().getClassLoader().getResourceAsStream("xmlPath")
// 获取当前项目路径
Document read = saxReader.read(this.getClass().getClassLoader().getResourceAsStream(xmlPath));
// 获取跟节点对象
Element rootElement = read.getRootElement();
List<Element> elements = rootElement.elements();
Object obj = null;
for (Element sonEle : elements) {
// 2.获取到每个bean配置 获取class地址
String sonBeanId = sonEle.attributeValue("id");
if (!beanId.equals(sonBeanId)) {
continue;
}
String beanClassPath = sonEle.attributeValue("class");
// 3.拿到class地址 进行反射实例化对象 ,使用反射api 为私有属性赋值
Class<?> forName = Class.forName(beanClassPath);
obj = forName.newInstance();
// 拿到成员属性
List<Element> sonSoneleme = sonEle.elements();
//循环遍历节点,这里就是遍历属性值
for (Element element : sonSoneleme) {
//属性名称
String name = element.attributeValue("name");
//属性值
String value = element.attributeValue("value");
// 使用反射api 为私有属性赋值
//下面是去拿到属性名为name的属性
Field declaredField = forName.getDeclaredField(name);
//允许向私有成员赋值
declaredField.setAccessible(true);
//对当前属性设置值---向私有属性赋值
declaredField.set(obj, value);
}
}
return obj;
}
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException,
IllegalArgumentException, IllegalAccessException, InstantiationException, DocumentException {
//设置读取根路径下的user.xml,下面有
ClassPathXmlApplicationContext appLication = new ClassPathXmlApplicationContext("user.xml");
//获取user1这个bean
Object bean = appLication.getBean("user1");
UserEntity user = (UserEntity) bean;
System.out.println(user.getUserId() + "----" + user.getUserName());
}
}
user.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="user1" class="com.itmayiedu.entity.UserEntity">
<property name="userId" value="0001"></property>
<property name="userName" value="LLL丶Blog"></property>
</bean>
<bean id="user2" class="com.itmayiedu.entity.UserEntity">
<property name="userId" value="0002"></property>
<property name="userName" value="张三"></property>
</bean>
</beans>
这里运行之后控制台会输出
0001----LLL丶Blog
实现了SpringIOC中的自动注入