applicationContext.xml
<beans>
<bean id="user1" class="com.company.User">
<property name="userId" value="1"></property>
<property name="userName" value="李四"></property>
</bean>
<bean id="user2" class="com.company.User">
<property name="userId" value="2"></property>
<property name="userName" value="张三"></property>
</bean>
</beans>
User.java
package com.company;
/**
* 手写springioc
*
* @author 000
*
*/
public class User {
private String userId;
private String userName;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public String toString() {
return "User [userId=" + userId + ", userName=" + userName + "]";
}
}
ClassPathXmlApplicationContext.java
package com.company;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class ClassPathXmlApplicationContext {
private String configFilePath;
public ClassPathXmlApplicationContext(String configFilePath) {
this.configFilePath = configFilePath;
}
/*
* dom4j解析
*/
public Object getBean(String id) throws Exception {
// 解析xml
SAXReader reader = new SAXReader();
InputStream inputStream = ClassLoader.getSystemResourceAsStream(configFilePath);
Document document = reader.read(inputStream);
if (document == null) {
return null;
}
// 从项目根目录下读取
Element root = document.getRootElement();
// 获取节点资源
List<Element> list = root.elements();
if (list.size() <= 0) {
return null;
}
Object obj = null;
for (Element element : list) {
String idString = element.attributeValue("id");
if (!id.equals(idString)) {
continue;
}
// 获取bean的class地址
String classString = element.attributeValue("class");
// 发射实例化bean
Class<?> class1 = Class.forName(classString);
obj = class1.newInstance();
// 获取子类对象
List<Element> elements = element.elements();
if (elements.size() <= 0) {
return null;
}
for (Element element2 : elements) {
String name = element2.attributeValue("name");
System.out.println(name);
String value = element2.attributeValue("value");
// 使用反射为对象赋值
Field field = class1.getDeclaredField(name);
field.setAccessible(true);
field.set(obj, value);
}
}
return obj;
}
}