Java architecture decryption-Self-Implementation of ioc in Spring framework

Source: Internet
Author: User

Java architecture decryption-Self-Implementation of ioc in Spring framework

In java Development, SSH is often used as the framework. In this framework, what we first came into contact with is the magic Spring, although many predecessors mentioned that Spring is a collection of N multiple public codes, it is a collection of good ideas that we wanted to implement or have implemented long ago, but as a qualified engineer, how can I not understand the underlying implementation of spring! Today, let's explore how Spring completes IOC and build a simple Spring framework!

1. Bean definition in Spring

Function: beans used in spring all have certain public attributes. This class is the definition of public attributes.

 

Package com. my. spring;/*** @ Description: definitions of common classes used by Spring * @ ClassName: BeanDefinition * @ Project: MySpring * @ Author: xvshu * @ Date: february 28, 2015 */public class BeanDefine {public String id; public String className; public BeanDefine (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 ;}}

 

2, assembly Class 2.1, XML assembly class

Purpose: assemble the Xml configuration in spring, which is injection.

 

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. extends entexception; 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
 
  
BeanList = new ArrayList
  
   
(); Map
   
    
Sigletions = new HashMap
    
     
(); Public ClassPathXMLApplicationContext (String fileName) {// read the beanthis managed in the configuration file. readXML (fileName); // instantiate beanthis. instancesBean (); // annotation processor this. annotationInject ();}/*** read Bean configuration file * @ param fileName * @ return */@ SuppressWarnings (unchecked) public void readXML (String fileName) {Document document = null; SAXReader saxReader = new SAXReader (); try {ClassLoader classLoader = Thread. currentThread (). getContextClassLoader (); document = saxReader. read (classLoader. getResourceAsStream (fileName); Element beans = document. getRootElement (); for (Iterator
     
      
BeansList = beans. elementIterator (); beansList. hasNext ();) {Element element = beansList. next (); BeanDefine bean = new BeanDefine (element. attributeValue (id), element. attributeValue (class); beanList. add (bean) ;}} catch (incluentexception e) {log.info (An error occurred while reading the configuration file ....);}} /*** instantiate Bean */public void instancesBean () {for (BeanDefine bean: beanList) {try {sigletions. put (bean. getId (), Class. forName (bean. getClas SName ()). newInstance ();} catch (Exception e) {log.info (An error occurred while instantiating the Bean ...);}}} /*** annotation processor ** if the annotation ZxfResource is configured with the name attribute, the instance reference to be injected is obtained based on the name specified by the name. If the annotation ZxfResource * is not configured with the name attribute, scan the configuration file according to the property type to obtain the instance reference to be injected **/public void annotationInject () {for (String beanName: sigletions. keySet () {Object bean = sigletions. get (beanName); if (bean! = Null) {this. propertyAnnotation (bean); this. fieldAnnotation (bean) ;}}/ *** handle the annotation added to the set Method * @ param bean processed bean */public void propertyAnnotation (Object bean) {try {// get the description of its properties PropertyDescriptor [] ps = Introspector. getBeanInfo (bean. getClass ()). getPropertyDescriptors (); for (PropertyDescriptor proderdesc: ps) {// get all set Method setter = proderdesc. getWriteMethod (); // determines whether the set method defines the annotation if (setter! = Null & setter. isAnnotationPresent (ZxfResource. class) {// obtain the current annotation and determine whether the name attribute is empty. getAnnotation (ZxfResource. class); String name =; Object value = null; if (resource. name ()! = Null &&!. Equals (resource. name () {// get the content of the name attribute of the annotation name = resource. name (); value = sigletions. get (name);} else {// if the name attribute is not specified for the current annotation, The for (String key: sigletions. keySet () {// determines whether the type of the current attribute exists in the configuration file if (proderdesc. getPropertyType (). isAssignableFrom (sigletions. get (key ). getClass () {// obtain the instance object value = sigletions that matches the type. get (key); break ;}}// allow access to the private method setter. setAccessible (true); // inject the referenced object into the property setter. invoke (bean, value );} Catch (Exception e) {log.info (Exception occurred when parsing the set Method annotation ..........);}} /*** process the Annotation on the field * @ param bean processed bean */public void fieldAnnotation (Object bean) {try {// obtain all of its Field descriptions Field [] fields = bean. getClass (). 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 of the current attribute exists in the configuration file if (f. getType (). isAssignableFrom (sigletions. get (key ). getClass () {// obtain the instance object value = sigletions that matches the type. get (key); break ;}}// allow access to the private field f. setAccessible (true); // inject the referenced object into the attribute f. set (bean, value) ;}} catch (Exception e) {log.info (field annotation parsing Exception ..........);}} /*** get the corresponding bean instance in Map * @ param beanId * @ return */public Object getBean (String beanId) {return sigletions. get (beanId );}}
     
    
   
  
 


2.2, annotation assembly

Purpose: inject annotation-marked parts in spring, which is a custom annotation.

 

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 annotation * @ ClassName: ZxfResource * @ Project: MySpring * @ Author: xvshu * @ Date: february 28, 2015 * // run @ Retention (RetentionPolicy. RUNTIME) // applicable to the annotation (field and method) @ Target ({ElementType. FIELD, ElementType. METHOD}) public @ interface ZxfResource {// name attribute of the annotation public String name () default ;}

3. Configuration File

 

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 annotation * @ ClassName: ZxfResource * @ Project: MySpring * @ Author: xvshu * @ Date: february 28, 2015 * // run @ Retention (RetentionPolicy. RUNTIME) // applicable to the annotation (field and method) @ Target ({ElementType. FIELD, ElementType. METHOD}) public @ interface ZxfResource {// name attribute of the annotation public String name () default ;}

4. Test class

Similar to common spring classes

Class link result diagram:

 

Test class:

 

public static void main(String[] args) {ClassPathXMLApplicationContext path = new ClassPathXMLApplicationContext(configAnnotation.xml);TestServiceImpl userService =(TestServiceImpl)path.getBean(TestService);userService.show();}

Test results:

 

Summary:

In our programming, there are many frameworks summarized by our predecessors. We can stay at the level of use in the early stage, but to enter the in-depth development, we need to understand the deep structure of this framework. This is not to allow us to create it again, but to fully sum up the experience of our predecessors to better use this tool. As the saying goes, we know ourselves, know ourselves, and know what we are capable, this is the process of knowing ourselves and ourselves. For other principles of spring technology, please look forward to my series of blogs!

 

 

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.