"SSH Advanced path" Step by step refactoring container implementation Spring Framework-completely encapsulated for simple and flexible Spring Framework (11)

Source: Internet
Author: User
Tags xpath

Folder
"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 simple and flexible Spring Framework (11)


Post "SSH Advanced path" step-by-step refactoring container implementation Spring Framework-starting with a simple container (eight), we encapsulate a particularly crude container in order to remove the dependency of the interface on the detailed implementation.
Blog "Advanced SSH Path" step by step refactoring container implementation of spring framework--to solve two kinds of schemes of container "intrusive" management of components--active lookup and control inversion (ix), we use control inversion to remove the component dependency on the container.

Blog "Advanced SSH Path" step by step refactoring container implementation of the spring framework-configuration file + reflection implementation of the IOC container (10), we implement the read configuration file, as well as the container to create the object of the flexible, simple IOC.

The goal of this blog post is not only to resemble spring, but also to be like spring, further encapsulating the object's dependencies .

We know that the spring framework is not only able to create objects from the configuration, but also to create dependencies between objects based on configuration. Depending on the object

Depends on how the relationship is configured, 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 ">  <property name=" DAO "ref=" DAO "></property>  </bean></beans>

We found two more properties in the Config file: property and ref, which expressed the need for service to be dependent on DAO, so we need to inject DAO

To the service, how to do it? We just need to build a javabean like a storage bean to:

public class PropertyDefinition {private string Name;private string Ref;public propertydefinition (string name, string ref {this.name = Name;this.ref = ref;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String GetRef () {return ref;} public void SetRef (String ref) {this.ref = ref;}}

with JavaBean, we just need to focus on how to inject values into the properties of a bean object. We can use introspection to manipulate bean class properties,

Thing The general practice is to get the BeanInfo information of an object through the class Introspector, and then get the descriptive narrator of the property by BeanInfo

(PropertyDescriptor), this property describes the narrator to obtain the corresponding Getter/setter method of a property, and then we can pass the inverse

To invoke these methods, and finally inject the reference object into the property.

Import Java.beans.introspector;import Java.beans.propertydescriptor;import Java.lang.reflect.method;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;/** * Container * * @author Liang * */publ IC class Classpathxmlapplicationcontext implements Beanfactory {//for storing beanprivate list<beandefinition> Beandefines = new arraylist<beandefinition> ()///For storing bean instance private map<string, object> sigletons =new Hashmap<string, object> ();p ublic classpathxmlapplicationcontext (String filename) {this.readxml (fileName); This.instancebeans (); This.injectobject ();} /** * The value of the Bean object is injected */private void Injectobject () {for (beandefinition beandefinition:beandefines) {Object Bean = Sigleto Ns.get (Beandefinition.getid ()), if (bean! = null) {try {///through Introspector to obtain the bean's definition information, and then obtain the descriptive narrative information of the property, Returns an array of propertydescriptor[] PS = Introspector.getbeaninfo (bean. GetClass ()). Getpropertydescriptors (); for (PropertyDefinition PropertyDefinition:beanDefinition.getPropertys ()) { for (PropertyDescriptor properdesc:ps) {if (Propertydefinition.getname (). Equals (Properdesc.getname ()))) {// Gets the setter method of the property, Privatemethod setter = Properdesc.getwritemethod (); if (setter = null) {Object value = Sigletons.get (Propertydefinition.getref ());//Consent to access private method setter.setaccessible (True); /inject the Reference object into the attribute Setter.invoke (bean, value); }break;}}}} catch (Exception e) {e.printstacktrace ();}}}} /** * Complete the bean instantiation */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 resource, get Document Object Document DOC =Saxbuilder.build (This.getclass (). getClassLoader (). getResourceAsStream (FileName));//Get the 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 config file for beanfor (int i = 0; i < listbean.size (); i++) {//The Bean sub-element under the root element beans as a new child-root element Elementbean = (Element) Listbean.get (i);//Gets the id attribute value string id = elementbean.getattributevalue ("id");//Gets the class Property value string Clazz = Elementbean.getattributevalue ("class"); Beandefinition beandefine = new Beandefinition (id,clazz);//Get all property sub-elements under sub-root element bean list ListProperty = Elementbean.getchildren ("property");//traverse the child element collection (that is, traverse the property element) for (int j = 0; J < Listproperty.size (), j + +) {//Get Property elements Element Elmentproperty = (Element) Listproperty.get (j);//Gets the name attribute value String propertyname = Elmentproperty.getattributevalue ("name");//Gets the ref attribute value string propertyref = Elmentproperty.getattributevalue ("ref"); PropertyDefinition propertydefinition = new PropertyDefinition (Propertyname,proPERTYREF); Beandefine.getpropertys (). Add (propertydefinition);} 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);}}


at this point we are able to remove the set method of the service interface.
Public interface Service {public void Servicemethod ();}


There is only part of the code here that you can download in the links below.

Summarize


After four blog post refactoring, we have implemented a spring prototype that will allow us to understand spring more deeply

In-depth learning spring buried the foreshadowing.


Source code Download


SSH Advanced Path Step-by-step refactoring container implementation Spring Framework-completely encapsulated for a simple and flexible spring Framework (11)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.