//加载配置文件
ApplicationContext ctx=new ClassPathXmlApplicationContext("Spring.xml");
Student student=(Student)(ctx.getBean("student1"));
System.out.println(student);
-
通过配置bean标签来完成对象的管理
-
id:对象名
-
class:对象的模板类。(所有交给IoC容器来管理的类必须有无参构造,因为Spring底层通过反射机制来创建对象,调用的是无参构造)
-
对象的成员变量通过property标签完成赋值
-
name:成员变量名
-
value:成员变量值(基本数据类型,String等,如果是其他的引用类型,不能用value)
-
ref:将IoC中的另外一个bean赋给当前的成员变量,即(DI方式)
-
-
IoC底层原理
-
读取配置文件,解析 XML
-
通过反射机制实例化配置文件中所有的 bean (以下)
-
public class ApplicationContextTestImp implements ApplicationContextTest { private Mapioc=new HashMap<>(); //初始化方法 public ApplicationContextTestImp(String path){ try { SAXReader reader=new SAXReader();//创建文件读取类 document document=reader.read(path);//读取路径 ./src/main/resources/Spring.xml Element root=document.getRootElement();//获取根节点 beans Iterator iterator=root.elementIterator();//获取beans迭代器 while (iterator.hasNext()){ Element element=iterator.next(); String id=element.attributevalue("id");//获取bean标签的id String classJName=element.attributevalue("class");//获取bean的class //通过反射机制创建对象 Class clazz=Class.forName(classJName); Constructor constructor= clazz.getConstructor();//获取无参构造函数 Object object= constructor.newInstance();//执行无参构造函数, 初始化对象 Iterator beanIter=element.elementIterator(); while(beanIter.hasNext()){ Element property=beanIter.next(); String name=property.attributevalue("name"); //获取property标签的 name value String valueStr=property.attributevalue("value"); String methodName="set"+name.substring(0,1).toUpperCase();//setid->setId Field field=clazz.getDeclaredField(name);//获取参数类型 Method method=clazz.getDeclaredMethod(methodName,field.getType()); //根据成员变量的数据类型 将value进行转换 Object value=null; if(field.getType().getName()=="long"){ value=Long.parseLong(valueStr); } if(field.getType().getName()=="int"){ value=Integer.parseInt(valueStr); } if(field.getType().getName()=="java.lang.String"){ value=valueStr; } //赋值成员变量 method.invoke(object,value); } ioc.put(id,object);//存放bean的id和对应的实例化对象 } System.out.println(document); } catch (documentException e) { e.printStackTrace(); }catch (ClassNotFoundException e){ e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } @Override public Object getBean(String id) { return ioc.get(id); } } -
通过运行时类获取bean
ApplicationContext ctx=new ClassPathXmlApplicationContext("Spring.xml"); Student student=(Student)ctx.getBean(Student.class);但这种方式存在一个问题,配置文件中一个数据类型的对象只能有一个实例(该类只能 有一个实例)。
-



