Spring's dependency injection refers to the behavior of giving the object's creation to the spring framework and injecting the properties on which the object depends. After learning dom4j, you can actually use dom4j and reflection to do a small demo to simulate the spring framework's functionality. Here are the specific steps:
The first step is to write the configuration file. The configuration file is written with the same writing rules as the spring configuration file Applicationcontext.xml:
<?XML version= "1.0" encoding= "UTF-8"?><!--applicationcontext.xml configuration file -<Beans> <BeanID= "Student1"class= "Com.xyy.domain.Student"> < Propertyname= "Name"value= "Hlhdidi"></ Property> < Propertyname= "Age"value= "+"></ Property> < Propertyname= "Teacher"ref= "Teacher1"></ Property> </Bean> <BeanID= "Teacher1"class= "Com.xyy.domain.Teacher"> < Propertyname= "Name"value= "CWB"></ Property> < Propertyname= "Classes"value= "39 Class High"></ Property> </Bean></Beans>
The second step, writing the JavaBean class, wrote two JavaBean, where there is a reference to the teacher class in the student class.
//Student Class Public classStudentImplementsserializable{PrivateString name; Private intAge ; PrivateTeacher Teacher; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } PublicTeacher Getteacher () {returnteacher; } Public voidSetteacher (Teacher Teacher) { This. Teacher =teacher; } @Override PublicString toString () {return"Student [name=" + name + ", age=" + Age + ", teacher=" + teacher + "]"; } }
//Teacher Class Public classTeacherImplementsserializable{PrivateString name; PrivateString classes; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicString getclasses () {returnclasses; } Public voidsetclasses (String classes) { This. Classes =classes; } @Override PublicString toString () {return"Teacher [name=" + name + ", classes=" + classes + "]"; } }
The third and most critical step is to write the Myclasspathxmlapplicationcontext class, which in this class does the following:
1. Get the stream of the XML file using the parameters passed in, and parse the document object with DOM4J
2. For the document object to get the root element object <beans> after the following <bean> tags are traversed to determine whether there is a matching ID.
3. If the corresponding ID is found, it is equivalent to finding an element elements, starting to create the object, first obtaining the class attribute, and using reflection to build the object based on the attribute value.
4. Traverse the property tag under the <bean> tab and assign a value to the attribute. Note that the properties of the Int,float type need to be handled separately. Because these properties are configured in the form of strings in the XML configuration, additional processing is required.
5. If the attribute property tag has a ref attribute, stating that the value of an attribute is an object, then the object of ref is obtained based on the ID (the value of the ref attribute), and the property is assigned a value.
6. Returns the created object, if there is no corresponding ID, or no sub-label <beans> will return null
The code is as follows:
Public classMyclasspathxmlapplicationcontext {PrivateString XMLName; PublicMyclasspathxmlapplicationcontext (String xmlname) { This. xmlname=XMLName; } PublicObject Getbean (String ID) {Object obj=NULL;//The declaration reference. //parsing the XMLSaxreader reader=NewSaxreader (); Try{Document Document= Reader.read ( This. GetClass (). getClassLoader (). getResourceAsStream (XMLName)); Element Root=document.getrootelement (); //Traverse. See if there is an element ID for the passed in parameter.list<element> elements =root.elements (); if(Elements.size () >0) { for(Element element:elements) {if(Element.attributevalue ("id"). equals (ID)) {//ID same Start creating object//creates an object with reflection.String Classname=element.attributevalue ("Class"); Class Beanclass=Class.forName (className); Obj=beanclass.newinstance (); //gets the properties of the child label.List<element> attributes=element.elements (); if(Attributes.size () >0) { for(Element attribute:attributes) {String name=attribute.attributevalue ("name"); Field field=Beanclass.getdeclaredfield (name); Field.setaccessible (true); if(Attribute.attribute ("ref")! =NULL) { //The value of this property is an object. Because the direct call to the Getbean method assigns a value to the object, the returned object must be an object of the bean parameter, so the cast will not be problematicString Refid=attribute.attributevalue ("ref"); Field.set (obj, Getbean (refID)); } Else { //This property value is a string. The int,float type variable is handled separately here. If not processed, the string type is directly assigned to the int type, which occurs classcastexceptionString value=attribute.attributevalue ("value"); //the type needs to be judged if(Value.matches ("[0-9]+")) { //integer intx=Integer.parseint (value); Field.set (obj, x); Continue; } if(Value.matches ("[0-9]* (\\.+) [0-9]*")) { //floating point number floaty=float.parsefloat (value); Field.set (obj, y); //Note Double can accept float type Continue; } field.set (obj, value);//working with String types } } } } } } } Catch(Exception e) {e.printstacktrace (); } returnobj; }}
Fourth step: Test.
@Test Public void testmyspring () { myclasspathxmlapplicationcontext applicationcontext=new Myclasspathxmlapplicationcontext ("Applicationcontext.xml"); System.out.println (Applicationcontext.getbean ("Student1")); }
Test results:
Student [Name=hlhdidi, age=13, Teacher=teacher [NAME=CWB, Classes= 39 class]]
Summarize:
DOM4J is a good tool for parsing XML, and parsing XML is a very important basic skill, which is very helpful for understanding the framework principle. Reflection, combined with XML file parsing, enables easy creation of any object in any class.
Using DOM4J and reflection to simulate the spring framework's dependency injection function