Assembly-DAYS02 of the Bean in the Spring Combat series

Source: Internet
Author: User

2.1 Reviews

The first day I wrote about the bean assembly was some basic syntax or some of the rules of spring itself, but I didn't delve into it. Next, let's discuss the details carefully. Compare the definition of a traditional class with the invocation of a method. This will reflect the characteristics of the IOC. The following UML diagram is one of the interfaces I defined earlier and one of my own implementations.

 Public Interface Compactdisc {    void  play ();} @Componentpublicclassimplements  Compactdisc {    private String title= "Enjoy the Music of Solitude"    ; Private String article= "To play a harmonious chapter";      Public void Play () {        System.out.println (title+article);    }}
Here is my test class
@RunWith (Springjunit4classrunner.  Class= cdplayconfig. class )publicclass  cdplayertest {    @Autowired    private  Compactdisc cd;    @Test    publicvoid  Test () {        cd.play ();    }
Here is my configuration file
@Configuration @componentscan  Public class Cdplayconfig {}
To recap briefly, Compactdisc annotated @component and told Spring that he was a bean. A bean is scanned by a @componescan annotation. Then the annotation @autowired auto-injection. The Assembly of the annotation-based bean can be explicitly shown in the following way: 2.2 Assembly of beans based on Java annotationsAt this point, when we remove the @componentscan annotation, we will report the following error:
 for dependency [Cn.czg.test.CompactDisc]: expected at least 1 bean which qualifies as Autowire candidate. Dependency annotations: {@org. springframework.beans.factory.annotation.Autowired (required=true)}
No corresponding bean is defined. Since this note was lost, it was no longer scanned. At this point, we can also explicitly complete this function. Now we can see that the error will occur when we lose this annotation, and we could implement the automatic Bean assembly based on the Java annotations. Very simple, Java provides the corresponding annotations, @Bean, generally used on the top of the method. We used the @componentscan annotations to complete the scan, and we created the beans automatically, but at this point we will modify the configuration files a little. Error after removing the scan annotations, but add @bean annotations.
@Configuration  Public class cdplayconfig {    @Bean    public  compactdisc sgtpeppers () {        return  New  sgtpeppers ();    }}
In any case, the function of @Bean is to obtain the strength of the interface object, we finally obtained the object instance in this method.
@Bean PublicIFoo getfooinstance () {intFloor = (int) Math.floor (Math.random () * 4); if(floor==1){        return NewFooDemo1 (); }Else if(floor==2){        return NewFooDemo2 (); }Else {        return NewFooDemo3 (); }}
As you can see, this feature is still very powerful, and with different conditions, you can create different instance objects. The above is the Java-based annotation of the bean assembly, now if my cdpalyer need Sgtpapers object, what should I do? At this point we are still based on the annotation configuration: And look at the following code:
@Configuration  Public class cdplayerconfig {    @Bean    public  compactdisc compactdisc () {        return New sgtpeppers ();    }    @Bean    public  cdplayer cdplayer () {        returnnew  CDPlayer (Compactdisc ());}    }
2.3 Java annotation-based injection (constructor injection/attribute injection)

The code above completes the injection of Comoactdisc. It is necessary to note that the constructor of the CDPlayer object appears to be calling the method Compactsic (), which returns an instance of the Sgtpapers object. However, in spring, because the @bean annotation exists, it blocks the invocation of the method and returns the instance object Sgtpapers created by the method directly. If the above code is modified:
@Configuration Public classCdplayerconfig {@Bean PublicCompactdisc Compactdisc () {return Newsgtpeppers (); } @Bean PublicCDPlayer CDPlayer () {return NewCDPlayer (Compactdisc ()); } @Bean PublicCDPlayer Anothercdplayer () {return NewCDPlayer (Compactdisc ()); }}
In this case, if the call is made in the usual way, then because each constructor cdplayer the Compactdisc object, it produces multiple CDPlayer objects, and the spring End bean defaults to Singleton. Make sure that the same bean can be injected only if the application needs the bean.
@Bean  Public cdplayer CDPlayer (Compactdisc compactdisc) {    returnnew  CDPlayer ( COMPACTDISC);}
Perhaps the code above looks a little more intuitive. This actually passes through the Cdplay () method to a Compactdisc object and completes the injection through the constructor. And there is no direct relationship with @bean Compactdisc. A little modification of the code is the injection of setter attributes:
@Bean  Public cdplayer CDPlayer (Compactdisc compactdisc) {    cdplayer cdplayer=new  CDPlayer (compactdisc);    Cdplayer.setcompactdisc (COMPACTDISC);     return CDPlayer;}
2.4 XML-based assembly of beans this is relatively straightforward. For example, to assemble CDPlayer:
<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"; Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"; Xsi:schemalocation= "Http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd" ;>    <!--declares the bean, the constructor injects the Compactdisc object -    <BeanID= "CDPlayer"class= "Cn.czg.bean.CDPlayer">        <Constructor-argref= "Compactdisc"/>    </Bean>    <!--declaring an instance of Compactdisc -    <BeanID= "Compactdisc"class= "Cn.czg.bean.SgtPeppers"/></Beans>
2.5 Import Hybrid configuration When you start spring, all the beans need to be loaded into the spring container, and our beans above are configured in the Cdplayerconfig class, but not all beans need to be configured in this class. And if configured together, the entire configuration class is displayed and cumbersome. For example, now I need to define another configuration class to load different beans:
@Configuration  Public class cdconfig {    @Bean    public  compactdisc compactdisc () {        returnNew  sgtpapers ();    }}
But in the end, it will be introduced in a final configuration file. @Import annotations At this time show great divinity.
@Configuration @componentscan@import (cdconfig. class publicclass  cdplayerconfig {    @Bean    public  CDPlayer Compactdisc (Compactdisc compactdisc) {        returnnew  CDPlayer (COMPACTDISC);    }}
You can also group two configuration classes together to form a new configuration class
@Configuration @import ({cdconfig. class, Cdplayerconfig. class })publicclass  soundsystemconfig {}
Here we define the Blankdisc, the same also implements the interface Compactdisc.
 Public classBlankdiscImplementsCompactdisc {PrivateString title; PrivateString artist; PrivateList<string>tracks;  PublicBlankdisc (string title, string artist, list<string>tracks) {         This. title =title;  This. Artist =artist;  This. Tracks =tracks; }     Public voidPlay () {System.out.println ("Playing" + title + "by" +artist);  for(String track:tracks) {System.out.println ("-track:" +Track ); }        }}
At this point we do not want to use @bean to assemble the bean, but want to assemble it in the form of XML.
<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"; Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"; Xmlns:c= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/C"; Xsi:schemalocation= "Http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd" ;>    <BeanID= "Blankdisc"class= "Cn.czg.soundsystem.BlankDisc"C:_0= "Sgt.paper ' s lonely Hearts Club Blank"c:_1= "The Beatles">    <Constructor-arg>        <List>            <value>Sgt.paper ' s lonely Hearts Club Blank</value>            <value>HGSD Oijdasfjsa oiasf</value>            <value>SDFQ SGTFQ T Hyt</value>            <value>SDFQ SGTFQ T Hytsdarf</value>        </List>    </Constructor-arg>    </Bean></Beans>
In the above configuration, c:_0 or C:_1 0 and 1 is the index, that is, a multi-parameter case of the use of a way, such as the above field title and article the two fields can be written. Value can be described more flexibly. The following is the value of the parameter in the list. At this point we also want to load the configuration file and XML into the spring file together, and then use the importsource annotation
@Configuration @componentscan@import (cdconfig. class ) @ImportResource ("Classpath:applicationContext.xml")    publicclass  cdplayerconfig {    @Bean    public  cdplayer compactdisc (Compactdisc compactdisc) {         returnnew  CDPlayer (COMPACTDISC);}    }
2.5 introduction of Javaconfig in XML at this point our configuration class can be configured directly in bean mode.

Assembly-DAYS02 of the Bean in the Spring Combat series

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.