Spring Core Learning (5) Inject bean bean-parsing dependency

Source: Internet
Author: User

Leading: Start learning Spring core ideas and learn with a cottage Lite spring code.


Content: 1. beanreference-Save a reference to the bean. 2. Call Createbean ()-lazy-init in Getbean (). This time we used the bean in the case of injecting beans, here we rewrite the abstractbeanfactory again, the rewritten abstractbeanfactory will have a list to save all the registered object name, And we are no longer the time to register to create the bean, and the beandefinition bean injection into the specific implementation, to implement lazy loading, because we know that is not registered after the use of this bean, so we put in the Getbean () and then instantiate the bean; Preinstantiatesingletons () in Abstractbeanfactory enables initialization of all beans The Autowirecapablebeanfactory class should be aware of the applypropertyvalues () function, where we want to inject more references in the class.

Beanreference:

public class Beanreference {private String name;private Object bean;public beanreference (String name) {this.name = name;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public Object Getbean () {return bean;} public void Setbean (Object bean) {This.bean = bean;}}
Beanfactory:

Public interface Beanfactory {Object Getbean (string name) throws Exception;void registerbeandefinition (string name, Beandefinition beandefinition) throws Exception;}
Abstractbeanfactory:

Public abstract class Abstractbeanfactory implements Beanfactory{private map<string, beandefinition> Beandefinitionmap = new concurrenthashmap<string, beandefinition> ();p rivate final list<string> Beandefinitionnames = new arraylist<string> (); @Overridepublic Object Getbean (String name) throws Exception { Beandefinition beandefinition = beandefinitionmap.get (name), if (beandefinition = = null) throw new IllegalArgumentException ("No Bean named" + name + "is defined"); Object bean = Beandefinition.getbean (); if (bean = = null) Bean = Docreatebean (beandefinition); return bean;} @Overridepublic void Registerbeandefinition (String name,beandefinition beandefinition) throws Exception{//todo This is no longer the time to create the bean, and the beandefinition bean injection into a specific implementation, to implement lazy loading beandefinitionmap.put (name, beandefinition); Beandefinitionnames.add (name);} public void Preinstantiatesingletons () throws Exception {for (iterator<string> it = This.beanDefinitionNames.iterator (); It.hasnext ();) {String Beanname = (STring) It.next (); Getbean (Beanname);}} /** * Initialize Bean * @param beandefinition * @return * */protected abstract Object Docreatebean (beandefinitio N beandefinition) throws Exception;}

Autowirecapablebeanfactory:

/** * can automatically load content of Beanfactory * @author Acer * */public class Autowirecapablebeanfactory extends abstractbeanfactory{@Overrid eprotected Object Docreatebean (beandefinition beandefinition) throws Exception{object Bean = createbeaninstance ( beandefinition);//notice, we are here to complete the bean Injection Beandefinition.setbean (bean); Applypropertyvalues (bean, beandefinition); return bean;} Protected Object createbeaninstance (Beandefinition beandefinition) throws Exception {return Beandefinition.getbeanclass (). newinstance ();} protected void Applypropertyvalues (Object bean, beandefinition mbd) throws Exception {for (PropertyValue propertyvalue:m Bd.getpropertyvalues (). Getpropertyvaluelist ()) {Field Declaredfield = Bean.getclass (). Getdeclaredfield ( Propertyvalue.getname ());d eclaredfield.setaccessible (true); Object value = Propertyvalue.getvalue (); if (value instanceof beanreference) {beanreference beanreference = (beanreference) Value;value = Getbean (BeanReference.getName () );} Declaredfield.set (bean, Value);}}}

HelloWorldService:

public class HelloWorldService {    private String text;        Private Outputservice Outputservice;    public void HelloWorld () {    outputservice.output (text);    }    public void SetText (String text) {        this.text = text;    }        public void Setoutputservice (Outputservice outputservice) {    this.outputservice = Outputservice;    }}
Outputservice:

public class Outputservice {private helloworldservice helloworldservice;public void output (String text) { Assert.assertnotnull (HelloWorldService); System.out.println (text);} public void Sethelloworldservice (HelloWorldService helloworldservice) {this.helloworldservice = HelloWorldService;}}

Beanfactorytest:

public class Beanfactorytest {@Testpublic void Testpreinstantiate () throws exception{//1. Read Configuration Xmlbeandefinitionreader Xmlbeandefinitionreader = new Xmlbeandefinitionreader (new Resourceloader ()); Xmlbeandefinitionreader.loadbeandefinitions ("Tinyioc.xml");//2. Initialize beanfactory and register beanabstractbeanfactory Beanfactory = new Autowirecapablebeanfactory (); for (map.entry<string, beandefinition> beanentry: Xmlbeandefinitionreader.getregistry (). EntrySet ()) Beanfactory.registerbeandefinition (BeanEntry.getKey (), Beanentry.getvalue ());//3. Initialize Beanbeanfactory.preinstantiatesingletons ();//4. Get Beanhelloworldservice HelloWorldService = (helloworldservice) beanfactory.getbean ("HelloWorldService"); Helloworldservice.helloworld ();} @Testpublic void Testlazy () throws Exception {//1. Read configuration Xmlbeandefinitionreader xmlbeandefinitionreader = new Xmlbeandefi Nitionreader (New Resourceloader ()); Xmlbeandefinitionreader.loadbeandefinitions ("Tinyioc.xml");//2. Initialize beanfactory and register beanabstractbeanfactory beanfactory = nEW autowirecapablebeanfactory (); for (map.entry<string, beandefinition> beanentry: Xmlbeandefinitionreader.getregistry (). EntrySet ()) Beanfactory.registerbeandefinition (BeanEntry.getKey (), Beanentry.getvalue ());//3. Get Beanhelloworldservice HelloWorldService = (helloworldservice) beanfactory.getbean ("HelloWorldService"); Helloworldservice.helloworld ();}}

Tinyioc.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" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= " Http://www.springframework.org/schema/tx "xmlns:context=" Http://www.springframework.org/schema/context "xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ SPRING-BEANS-2.5.XSDHTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-2.5.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-2.5.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-2.5.xsd "> <bean name=" outputservice "class=" Step5.test.OutputService "> <property name = "HelloWorldService" ref= "HelloWorldService" ></property> </bean> <bean name= "HelloWorldService "class=" Step5.test.HelloWorldService "> <property name=" text "value=" Hello world! From step5! " ></property> <property name= "Outputservice" ref= "Outputservice" ></property> &LT;/BEAN&GT;&L T;/beans>





Spring Core Learning (5) Inject bean bean-parsing dependency

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.