The Java architecture decrypts the IOC self-implementation of the--spring framework

Source: Internet
Author: User

In Java development, often used in the framework of SSH, and in this framework, we first touched by the magic of spring, although there are more than N, said Spring is a collection of n many common code, is to help us to achieve, we have long ago to achieve or have achieved a good idea of the collection , but as a qualified engineer, how can not understand the bottom of spring implementation of it! Today we will explore how spring completes the IOC work and make a simple spring framework for ourselves!

the definition of beans in 1,spring

Role: Beans used in spring have some common properties, which are definitions of public properties

<span style= "FONT-SIZE:18PX;" >package com. my.spring;/** * @Description: Spring uses the class common part definition * @ClassName: beandefinition * @Project: myspring * @Author: Xvshu * @Date: February 28, 2015 */public class Beandefine {public string Id;public string Classname;public beandefine (string ID, String Classna Me) {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;}} </span>

2, Assembly class2.1,xml Assembly Class

Role: The Assembly of classes for XML configuration in spring is actually injected

<span style= "FONT-SIZE:18PX;" >package com. My.spring;import Java.beans.introspector;import Java.beans.propertydescriptor;import Java.lang.reflect.Field; Import Java.lang.reflect.method;import java.util.arraylist;import java.util.hashmap;import java.util.Iterator; Import Java.util.list;import java.util.map;import Org.apache.log4j.logger;import Org.dom4j.document;import Org.dom4j.documentexception;import org.dom4j.element;import org.dom4j.io.saxreader;import com. my.test.testserviceimpl;/** * @Description: annotation principle in Spring * @ClassName: Classpathxmlapplicationcontext * @Project: myspring * @Author: Xvshu * @Date: February 28, 2015 */public class Classpathxmlapplicationcontext {Logger log = Logger.getlogger (Classpathxmlapplicationcontext.class); list<beandefine> beanlist = new arraylist<beandefine> (); map<string, object> sigletions = new hashmap<string, object> ();p ublic Classpathxmlapplicationcontext ( String filename) {//Read beanthis.readxml (fileName) managed in the configuration file;//Instantiate Beanthis.instaNcesbean ();//Note Processor this.annotationinject ();} /** * Read Bean config file * @param fileName * @return */@SuppressWarnings ("unchecked") public void ReadXML (String fileName) {documen t document = null; Saxreader Saxreader = new Saxreader (); try {ClassLoader ClassLoader = Thread.CurrentThread (). Getcontextclassloader (); Document = Saxreader.read (Classloader.getresourceasstream (fileName)); Element beans = document.getrootelement (); for (iterator<element> beanslist = Beans.elementiterator (); Beanslist.hasnext ();) {element element = Beanslist.next (); Beandefine bean = new Beandefine (Element.attributevalue ("id"), Element.attributevalue ("class")); Beanlist.add (bean);}} catch (Documentexception e) {log.info ("Error reading configuration file ....");}} /** * Instantiate bean */public void Instancesbean () {for (Beandefine bean:beanlist) {try {sigletions.put (), Bean.getid Name (Bean.getclassname ()). newinstance ());} catch (Exception e) {log.info ("Instantiation bean Error ...");}}} /** * Annotation Processor * If annotation Zxfresource is configured with the Name property, the instance reference to be injected is obtained according to the name specified by name, if the annotation zxfresource* If the Name property is not configured, scan the configuration file for the instance reference to be injected according to the type of the property (*/public void Annotationinject () {for (String BeanName:sigletions.keySet ()) { Object bean = Sigletions.get (beanname), if (bean!=null) {this.propertyannotation (bean); this.fieldannotation (bean);}}} /** * Handles annotations added in the Set method * @param bean processed by beans */public void propertyannotation (Object bean) {try {//Gets a description of its properties PropertyDescriptor [] PS = Introspector.getbeaninfo (Bean.getclass ()). Getpropertydescriptors (); for (PropertyDescriptor proderdesc:ps) {/ /Get all set methods method setter = Proderdesc.getwritemethod ();//Determine if the Set method defines the annotation if (Setter!=null && Setter.isannotationpresent (Zxfresource.class)) {//Gets the current annotation and determines whether the Name property is empty Zxfresource resource = Setter.getannotation ( Zxfresource.class); String name = ""; Object value = Null;if (Resource.name ()!=null&&! "". Equals (Resource.name ())) {//Gets the contents of the Name property of the callout name = Resource.name (); value = Sigletions.get (name);} else{//If the current annotation does not specify a Name property, match for (String Key:sigletions.keySet ()) {//To determine whether the type that the current property belongs to has an if in the configuration file ( Proderdesc.getpropertytype (). isassignAblefrom (Sigletions.get (key). GetClass ())) {//Get type matching instance object value = Sigletions.get (key); Allow access to Private method setter.setaccessible (TRUE);//Inject Reference object into attribute Setter.invoke (bean, value); }}} catch (Exception e) {Log.info ("Set method annotation parsing exception ...");}} /** * Handling Annotations on fields * @param bean processed by beans */public void fieldannotation (Object bean) {try {//Get all of its field descriptions field[] fields = bean.ge Tclass (). GetFields (); for (Field f:fields) {if (F!=null && f.isannotationpresent (zxfresource.class)) { Zxfresource resource = f.getannotation (Zxfresource.class); String name = ""; Object value = Null;if (Resource.name ()!=null&&! "". Equals (Resource.name ())) {name = Resource.name (); value = Sigletions.get (name);} Else{for (String key:sigletions.keySet ()) {//Determines whether the type to which the current property belongs exists if (F.gettype (). IsAssignableFrom (Sigletions.get ( Key). GetClass ()) {//Get type Match Instance object value = Sigletions.get (key); break;}} Allow access to private field f.setaccessible (true);//Inject Reference object into attribute F.set (bean, Value);}}} catch (Exception e) {log.info ("field annotation parsing exception ...");} /** * Gets the corresponding bean real in the mapExample * @param beanid * @return */public Object getbean (String beanid) {return sigletions.get (Beanid);}} </span>


2.2, annotation Assembly class

Role: Injecting a part of the annotation tag in spring, which is a custom annotation

<span style= "FONT-SIZE:18PX;" >package com. My.spring;import Java.lang.annotation.elementtype;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import java.lang.annotation.target;/** * @Description: Define annotations * @ClassName: Zxfresource * @Project: myspring * @Author: Xvshu * @Date: February 28, 2015 *///execute @retention at runtime (retentionpolicy.runtime)//annotations Apply Use local (field and method) @Target ({Elementtype.field, elementtype.method}) public @interface Zxfresource {//Annotation Name property public String Name () Default "";} </span>

3, configuration file

<span style= "FONT-SIZE:18PX;" >package com. My.spring;import Java.lang.annotation.elementtype;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import java.lang.annotation.target;/** * @Description: Define annotations * @ClassName: Zxfresource * @Project: myspring * @Author: Xvshu * @Date: February 28, 2015 *///execute @retention at runtime (retentionpolicy.runtime)//annotations Apply Use local (field and method) @Target ({Elementtype.field, elementtype.method}) public @interface Zxfresource {//Annotation Name property public String Name () Default "";} </span>

4, test class

The same way as the normal spring class.

Class Relationship result diagram:



Test class:

<span style= "FONT-SIZE:18PX;" >public static void Main (string[] args) {classpathxmlapplicationcontext path = new Classpathxmlapplicationcontext (" Configannotation.xml "); Testserviceimpl UserService = (Testserviceimpl) path.getbean ("Testservice"); Userservice.show ();} </span>

Test results:


Summary:

In our programming, there are many of our predecessors summed up the framework, we stay at the level of use is completely possible, but to enter into deep development, it is necessary to understand the deep structure of the framework, this is not let us create it again, but to fully summarize the experience of predecessors to better use this tool, as the saying goes, The enemy can victorious, this is the process of knowing the enemy, about spring technology, other principles, please look forward to my series blog!


SOURCE Download: myspring

The Java architecture decrypts the IOC self-implementation of the--spring framework

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.