Directory
"SSH Advanced path" Step by step refactoring container implementation Spring Framework-starting with a simple container (eight)
"SSH Advanced path" Step by step refactoring container to implement spring framework--two schemes to solve the "intrusive" management of containers for components--active lookup and control inversion (ix)
"SSH Advanced path" Step by step refactoring container implementation Spring Framework-configuration file + Reflection implementation IOC container (10)
"SSH Advanced path" Step by step refactoring container implementation Spring Framework-completely encapsulated for a simple and flexible spring Framework (11) (not updated)
On the previous blog "Advanced SSH Path" step-by-step reconstruction of the container implementation of the spring framework-starting from a simple container (eight), we want to remove the connection
The dependency of the port on the specific implementation encapsulates a particularly crude container.
On the "SSH Advanced path" step-by-step refactoring container to implement the spring framework--the two solutions to the "intrusive" management of the container to the component--master
Dynamic lookup and Control inversion (ix), we use control inversion to remove the component's dependency on the container.
simple configuration, Reflection
When the container was initialized in the previous post, use new to power the object, this blog post we use the configuration file + reflect the strength of the object, further sealing
Load Drop the coupling degree of the lower container and the component. Let's look at the configuration file first.
<?xml version= "1.0" encoding= "UTF-8"?><beans> <bean id= "DAO" class= " Com.tgb.container.dao.impl.Dao4MySqlImpl "/> <bean id=" service "class=" Com.tgb.container.service.impl.ServiceImpl "/></beans>
See the above configuration file, in addition to the namespace is not, and the spring configuration file is very similar, below we use dom4j or jdom to read
Configuration Text The configuration file, and the configuration class takes advantage of reflection instantiation. This example we use the Jdom, you can also use dom4j to try. Below I
See a under Read the code for the configuration file:
Public interface Beanfactory {Object Getbean (String ID);}
Import Java.util.hashmap;import java.util.list;import Java.util.map;import Org.jdom.document;import Org.jdom.element;import Org.jdom.input.saxbuilder;import Org.jdom.xpath.xpath;import Com.tgb.container.dao.Dao; Import com.tgb.container.service.service;/** * Load config file from Classpath * * @author Liang * */public class Classpathxmlapplicationcont Ext implements Beanfactory {//For storing beanprivate map<string, object> beans = new hashmap<string, object> ();p UBL IC classpathxmlapplicationcontext (String filename) {this.readxml (filename);} Parses the XML file, puts the configured beasn into container by reflection, and implements the dependency injection private void ReadXML (String fileName) {//Create Saxbuilder Object Saxbuilder Saxbuilder = new Saxbuilder ();//Read resource, Get Document object document Doc;try {doc = Saxbuilder.build (This.getclass (). getClassLoader (). getResourceAsStream (FileName));//Gets the root element elements Rootele = doc.getrootelement ();//Get all the child elements from the root element, Set up the Elements collection List Listbean = Xpath.selectnodes (Rootele, "/beans/bean");//traverse the collection of child elements of the root element, scan beanfor in the configuration file (int i = 0; i < Listbean . Size (); i++) {Element bean = (Element) listbean.get (i);//Gets the id attribute value string id = bean.getattributevalue ("id");//Gets the class Property value string Clazz = BEAN.G Etattributevalue ("class");//reflection, instantiation of Object o = Class.forName (clazz). newinstance (); Beans.put (ID, o);} Dependency management, here is not flexible, but the principle is the same service service = (service) beans.get ("service");D ao dao = (dao) beans.get ("DAO");//Dependency Injection, The service implementation relies on DAO's implementation Service.setdao (DAO);} catch (Exception e) {e.printstacktrace ();}} /** * Find Component * * @param ID * @return */@Overridepublic Object Getbean (String ID) {return beans.get (ID);}}
seeing the code above, we found that the method of reading the configuration file contains reflection, the code is too readable, and the object-oriented encapsulation is not enough
Bottom, let's further encapsulate the bean instantiation and dependency injection.
Encapsulating a bean instantiation
For further encapsulation, we encapsulate the properties of the configuration file into a JavaBean, in order to store our property values. As shown below:
public class Beandefinition {private string Id;private string Classname;public beandefinition (string ID, String className {this.id = Id;this.classname = ClassName;} Public String GetId () {return ID;} public void SetId (String id) {this.id = ID;} Public String GetClassName () {return className;} public void Setclassname (String className) {this.classname = ClassName;}}
Now we can do a further encapsulation of the bean instantiation.
Import Java.util.arraylist;import java.util.hashmap;import Java.util.list;import Java.util.map;import Org.jdom.document;import Org.jdom.element;import Org.jdom.input.saxbuilder;import Org.jdom.xpath.XPath;import Com.tgb.container.dao.dao;import com.tgb.container.service.service;/** * Container * * @author Liang * */public class ClassPath Xmlapplicationcontext implements Beanfactory {//For storing beanprivate list<beandefinition> beandefines = new ArrayList <BeanDefinition> ()///For storing bean instances private map<string, object> sigletons =new hashmap<string, object> ();p ublic classpathxmlapplicationcontext (String filename) {this.readxml (filename); This.instancebeans (); This.injectobject ();} /** * Dependency Injection, injecting values into the properties of the Bean object * Here is not flexible, but the principle is the same */private void Injectobject () {Service service = (service) this.sigletons.get (" Service ");D ao dao = (dao) this.sigletons.get (" DAO ");//Dependency injection, service implementation relies on DAO implementation Service.setdao (DAO);} /** * Completes the instantiation of the Bean */private Void Instancebeans () {for (beandefinition beandefinition:beAndefines) {try {if (beandefinition.getclassname ()! = NULL &&! "). Equals (Beandefinition.getclassname (). Trim ())) {Sigletons.put (Beandefinition.getid (), Class.forName ( Beandefinition.getclassname ()). newinstance ());}} catch (Exception e) {e.printstacktrace ();}}} /** * Read XML configuration file */private void ReadXML (String fileName) {//Create Saxbuilder object Saxbuilder saxbuilder = new Saxbuilder (); try {// Read resources, get Document Object Document DOC = Saxbuilder.build (This.getclass (). getClassLoader (). getResourceAsStream (FileName) ;//Get root element elements Rootele = doc.getrootelement ();//Get all the child elements from the root element, set up the element collection List Listbean = Xpath.selectnodes (Rootele, "/ Beans/bean ");//traverse the collection of child elements of the root element, scan beanfor in the configuration file (int i = 0; i < listbean.size (); i++) {Element bean = (Element) listbean.ge T (i);//Gets the id attribute value string id = bean.getattributevalue ("id");//Gets the class attribute value string clazz = Bean.getattributevalue ("class"); Beandefinition beandefine = new Beandefinition (id,clazz);//Add JavaBean to the collection Beandefines.add (Beandefine);}} catch (Exception e) {e.printstacktrace ();}}/** * Get Bean instance */@Overridepublic Object Getbean (String beanname) {return this.sigletons.get (beanname);}}
We know that containers are responsible not only for creating objects, but also for managing dependencies on objects, managing the life cycle of objects, and so on. We only implemented the container
Part of the flexible creation of objects, the dependency injection part is manually injected by us. The object's dependencies are not yet flexible, but we have been able to see the IOC's
Shadow, but the shape, has not reached the goal of likeness.
Next post "SSH Advanced path" Step by step refactoring container implementation Spring Framework-completely encapsulated for a simple and flexible spring Framework (11), Horse
On the delivery.
Source Download
"SSH Advanced path" Step by step refactoring container implementation Spring Framework-configuration file + Reflection implementation IOC container (10)