How the code analyzes spring management beans

Source: Internet
Author: User

In spring's first case, we already know how to give the bean to the spring container for management and how to get the bean from the spring container. So we have a question: How does spring create and manage beans? Now we're going to encode the principles of spring management beans.
This article is based on the first case of spring.
We are going to use dom4j to read the sping configuration file--beans.xml

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans"     xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"    xsi:schemalocation= "http// Www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/ Spring-beans.xsd ">    class=" Cn.itcast.service.impl.PersonServiceBean "></bean></ Beans>

Then you need to import the jar package required by dom4j into the project. The jar packages required for dom4j are:

    • Dom4j-1.6.1.jar
    • Jaxen-1.1-beta-6.jar

DOM4J read to such

class= "Cn.itcast.service.impl.PersonServiceBean" ></bean>

When such content is required, it is important to store the information of the bean being read into a JavaBean object. So we can create such a javabean--beandefinition.java under the Junit.test package with the following code:

/*** Save the information of the bean read to a JavaBean object * */ Public classbeandefinition {PrivateString ID; PrivateString ClassName;  Publicbeandefinition (String ID, string className) { This. ID =ID;  This. ClassName =ClassName; }     PublicString getId () {returnID; }     Public voidsetId (String id) { This. ID =ID; }     PublicString GetClassName () {returnClassName; }     Public voidsetclassname (String className) { This. ClassName =ClassName; }}

Next we'll create a spring container for the Intelligence podcast version to emulate the spring container. Create a new class--itcastclasspathxmlapplicationcontext.java under Junit.test with the following code:

/*** Wisdom Podcast version Spring container **/ Public classItcastclasspathxmlapplicationcontext {PrivateList<beandefinition> Beandefines =NewArraylist<beandefinition>(); Privatemap<string, object> sigletons =NewHashmap<string, object>();  Publicitcastclasspathxmlapplicationcontext (String filename) { This. ReadXML (filename);  This. Instancebeans (); }    /*** Complete the instantiation of the bean*/    Private voidInstancebeans () { 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 config file *@paramfilename*/    Private voidReadXML (String filename) {saxreader Saxreader=NewSaxreader (); Document Document=NULL; Try{URL Xmlpath= This. GetClass (). getClassLoader (). getresource (filename); Document=Saxreader.read (Xmlpath); Map<string, string> nsmap =NewHashmap<string, string>(); Nsmap.put ("NS", "Http://www.springframework.org/schema/beans");//Join a namespaceXPath xsub = Document.createxpath ("//ns:beans/ns:bean");//Create a Beans/bean query pathXsub.setnamespaceuris (NSMAP);//Set Namespacelist<element> beans = xsub.selectnodes (document);//get all bean nodes under a document             for(Element Element:beans) {String ID= Element.attributevalue ("id");//Get ID Property valueString clazz = Element.attributevalue ("class");//get the Class Property valueBeandefinition Beandefine =Newbeandefinition (ID, clazz);            Beandefines.add (Beandefine); }        } Catch(Exception e) {e.printstacktrace (); }    }    /*** Get Bean instance *@paramBeanname *@return     */     PublicObject Getbean (String beanname) {return  This. Sigletons.get (Beanname); }}

In this way, the spring container of the podcast version of the wisdom is created. Next we are going to test whether the spring container of the Preach Intelligence podcast can get the bean instance, just modify the code for the Springtest class:

 Public classspringtest {@Test Public voidTest () {//ApplicationContext is an interface//ApplicationContext ctx = new Classpathxmlapplicationcontext ("Beans.xml");//instantiate a spring container//Personservice Personservice = (personservice) ctx.getbean ("Personservice");//get bean from spring container//Personservice.save ();Itcastclasspathxmlapplicationcontext CTX=NewItcastclasspathxmlapplicationcontext ("Beans.xml");//instantiate a spring containerPersonservice Personservice = (personservice) ctx.getbean ("Personservice");//get bean from spring containerPersonservice.save (); }}

Testing the test () method, the Eclipse console prints as follows:

By writing code to dissect the principles of spring's management beans, we have a deep understanding of how the bean instances are created and managed within spring.

How the code analyzes spring management beans

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.