1.解析xml
2.使用beanid查找对应的xml节点 获取class 节点属性
3.使用java的反射机制初始化类
4.使用java的反射机制给私有属性赋值
import java.lang.reflect.Field;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class ClassPathXmlApplicationContext {
private static String Path;
private static String ID;
private static String CLASS;
private static String NAME;
private static String VALUE;
public void init(){
ID="id";
CLASS="class";
NAME="name";
VALUE="value";
}
public ClassPathXmlApplicationContext(String path){
init();
//获取spring读取文件名称
this.Path=path;
}
public Object getBean(String beanId) throws DocumentException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException{
//1.解析xml
if (StringUtils.isEmpty(beanId)) {
return null;
}
SAXReader saxReader = new SAXReader();
Document read = saxReader.read(this.getClass().getClassLoader().getResource(Path));
//拿到根节点
Element rootElement = read.getRootElement();
//获得所有二级节点
List<Element> elements = rootElement.elements();
for (Element element : elements) {
String id = element.attributeValue(ID);
if (!beanId.equals(id)) {
//结束本次循环
continue;
}
//2.使用beanid查找对应的xml节点 获取class节点属性
//从配置文件中获取bean
String attClass = element.attributeValue(CLASS);
//3.使用java的反色机制初始化类
Class<?> forName = Class.forName(attClass);
Object newInstance = forName.newInstance();
//4.获取属性
List<Element> sonEle = element.elements();
for (Element el : sonEle) {
String attrName = el.attributeValue(NAME);
String attrValue = el.attributeValue(VALUE);
//获取到私有属性
Field declaredField = forName.getDeclaredField(attrName);
declaredField.setAccessible(true);
declaredField.set(newInstance, attrValue);
}
return newInstance;
}
return null;
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, DocumentException {
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UserEntity user = (UserEntity) classPathXmlApplicationContext.getBean("user1");
System.out.println(user.toString()+"\t"+user.getUserName()+"\t");
}
}