Spring Learning Series (iii) assembling beans through Java code

Source: Internet
Author: User

The above combs through the annotations to complete the component scanning and automatic assembly, below to learn how to use the explicit configuration of the assembly bean

Second, assemble the Bean through Java class

The Helloworldconfig class is defined earlier, and using the @componentscan and @configuration annotations, @Configuration annotations indicate that the class is a Java configuration class that is used when getting the spring application context , tell spring to create the details of the bean, through @componentscan, we enable spring's automatic component scanning, now let's see if we explicitly configure the bean through the Java class, let's practice it with a music player case.

We play music, first we need a player, then we need music resources, first we define a player interface and music resource interface

 Package Com.seven.springTest.service; // player  Public Interface MediaPlayer {      void  play ();}
 Package Com.seven.springTest.service; // Music Resources  Public Interface Musicsource {    void  play ();}

This time playing music we are CD-ROM to play CDs music, we will implement the above interface,

 PackageCom.seven.springTest.service.impl;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.stereotype.Component;ImportCom.seven.springTest.service.MusicSource;ImportCom.seven.springTest.service.MediaPlayer;//defining the optical drive player Public classCDPlayerImplementsMediaPlayer {@Autowired//Define a music resource, where you declare the dependency that needs to be injected into the Musicsource by @autowired    PrivateMusicsource cd; @Override Public voidPlay () {//Play MusicCd.play (); }}

Implementing music resources as discs

 package   Com.seven.springTest.service.impl ; import   Com.seven.springTest.service.MusicSource;  public  class  Cdsource implements   Musicsource { private  String title = "Li Qi Xiang" ;     private  String artist = "Jay Chou" ; @Override  public  void   play () {System.out.println (" Playing "+ title +" by "+ Arti    ST); }}

So far we've completed the interface definition and implementation of the player, the music resource, and what kind of dependency do we have to tell spring which beans to create? In the first part, we implicitly tell Spring through @component annotations, and now we configure the Bean component with the Java class.

@Bean

@Bean note tells the spring function to return an object that needs to be registered as a bean in the spring application context, which contains the logic that produces the bean instance

 Packagecom.seven.springTest.Configuration;ImportOrg.springframework.context.annotation.Bean;ImportOrg.springframework.context.annotation.ComponentScan;Importorg.springframework.context.annotation.Configuration;ImportCom.seven.springTest.service.MusicSource;ImportCom.seven.springTest.service.MediaPlayer;ImportCom.seven.springTest.service.impl.CDPlayer;ImportCom.seven.springTest.service.impl.CDSource; @Configuration Public classMedieplayerconfig {@Bean//the Musicsource object returned by the method needs to be registered as a bean in the Spring application context     PublicMusicsource Cdsource () {return NewCdsource (); } @Bean//the MediaPlayer object returned by the method needs to be registered as a bean in the Spring application context     PublicMediaPlayer CDPlayer () {return NewCDPlayer (); }    }

In the Medieplayerconfig class, we only added the @configuration annotations, the previous @componentscan annotations were removed, the component scans were not configured to start spring, and the implementation classes of the interfaces did not add @component annotations. We use @bean annotations to tell spring which objects need to be registered as beans in the context of the spring application. The Cdsource () method returns an instance object of type Musicsource Cdsource, which is registered to the spring application context, and the same cdplayer () The MediaPlayer method returns an instance of the type CDPlayer registered in the Spring application context. Let's test it down.

 PackageCom.seven.springTest.main;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.annotation.AnnotationConfigApplicationContext;ImportCom.seven.springTest.Configuration.MediePlayerConfig;ImportCom.seven.springTest.Configuration.HelloWorldConfig;ImportCom.seven.springTest.service.MediaPlayer; Public classMediaplayertest { Public Static voidMain (string[] args) {//Loading the Java configuration class to get the Spring application contextApplicationContext AC =NewAnnotationconfigapplicationcontext (Medieplayerconfig.class); //Get playerMediaPlayer player= Ac.getbean (MediaPlayer.class); //PlayPlayer.play (); }}

When we get the player bean, we actually get the object CDPlayer returned by CDPlayer () in the Medieplayerconfig class, and in CDPlayer we rely on Musicsource, through @autowired annotations, Spring automatically injects the bean's dependency on the Musicsource, so in the test code we just get the instance player of the MediaPlayer object, and as for the player's dependencies, we don't know, it's injected by the spring container, This is just about player player, which is what spring brings to us, and we don't need to use code to manage the dependencies of objects, and all of the resources that we rely on have spring containers for us to inject.

With the development of technology, one day CD-ROM can also be inserted into the USB drive to play MP3 music, this time we come to realize a MP3 music resources

 PackageCom.seven.springTest.service.impl;ImportCom.seven.springTest.service.MusicSource; Public classMp3sourceImplementsMusicsource {PrivateString title = "Grandmother"; PrivateString artist = "Jay Chou"; @Override Public voidPlay () {//TODO auto-generated Method StubSystem.out.println ("MP3 Playing" + title + "by" +artist); }}

In the first part of automatic assembly, if spring finds that more than one bean satisfies the dependency, spring cannot choose, so if we define the implementation of the Mp3source, will this happen now? By running the program, we find that there is no effect on whether the CDPlayer bean is injected with musicsource dependency or cdsource. This is because we have told the spring-generated bean implementation logic in Medieplayerconfig by Cdsource (), so let's modify the next Cdsource ()

@Bean   // The Musicsource object returned by the method needs to be registered as the Bean public Musicsource Cdsource in the context of the spring application  ( {    // return Mp3source instance return    new  Mp3source ();}

We then run the test method, found that the output has become "==mp3 Playing grandmother by Jay Chou = =", the injection of dependent object implementation has changed, because Cdsource () is implemented in the return Mp3source instance.

As with previous @component, the Bean returned by the method that added the @bean annotation is also assigned an ID by default, with the same method name by default, such as the ID of the bean returned by the Cdsource () method as "Cdsource", and we can also specify the bean's ID. As follows:

@Bean (name= "Mycdplayer")      // The MediaPlayer object returned by the method needs to be registered as Bean Public in the spring application context MediaPlayer CDPlayer () {    returnnew  cdplayer ();}

This allows the bean to be retrieved by ID when it gets

 public  class   mediaplayertest { public  static  void   main (string[]        args) { //  load Java configuration class Get Spring app context  ApplicationContext ac = new  annotationconfigapplicationcontext ( Medieplayerconfig. class          //  Gets the bean by ID  MediaPlayer player= (        MediaPlayer) Ac.getbean ("Mycdplayer"  //  play      Player.play (); }}

In the above case, the CDPlayer bean is dependent on musicsource, and we declare the dependency of CDPlayer through @autowired in the CDPlayer class, which is also an implicit configuration through annotations. Let's do this with the Java configuration class.

In the case of an explicit configuration, because the bean configured in Medieplayerconfig is returned through a method, it needs to inject a dependency into the method that returns the object bean:

@Bean (name= "Mycdplayer")  // The MediaPlayer object returned by the method needs to be registered as Bean Public in the spring application context MediaPlayer CDPlayer () {    returnnew CDPlayer (Cdsource ());   // injecting dependencies through the object's constructor

Or

@Bean (name= "Mycdplayer")  // The MediaPlayer object returned by the method needs to be registered as Bean Public in the spring application context MediaPlayer CDPlayer (Musicsource musicsource) {    returnnew cdplayer (musicsource);   // injecting dependencies through the object's constructor

With the above 2 configuration, spring can complete the dependency injection on the Musicsource object in CDPlayer, and we define a bean configuration

@Bean (name= "Mycdplayer")  // The MediaPlayer object returned by the method needs to be registered as Bean Public in the spring application context MediaPlayer CDPlayer () {    returnnew CDPlayer (Cdsource ());   // injecting dependencies through the object's constructor } @Bean (name= "Othercdplayer")   // Define another Bean object, Public MediaPlayer Othercdplayer () {    returnnew  CDPlayer (Cdsource ());}

MediaPlayer interface adds a way to get playback resources

 Package Com.seven.springTest.service;  Public Interface MediaPlayer {    /**     * Gets the resource loaded by the player @return  musicsource     *    /Musicsource getresource ()    ; /**      * Play     *     /void  play ();

To solve the following, we modify the test code

 PackageCom.seven.springTest.main;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.annotation.AnnotationConfigApplicationContext;ImportCom.seven.springTest.Configuration.MediePlayerConfig;ImportCom.seven.springTest.Configuration.HelloWorldConfig;ImportCom.seven.springTest.service.MediaPlayer; Public classMediaplayertest { Public Static voidMain (string[] args) {//Loading the Java configuration class to get the Spring application contextApplicationContext AC =NewAnnotationconfigapplicationcontext (Medieplayerconfig.class); //Get playerMediaPlayer player = (MediaPlayer) ac.getbean ("Mycdplayer"); MediaPlayer Otherplayer= (MediaPlayer) ac.getbean ("Othercdplayer"); if(Player.getresource (). Equals (Otherplayer.getresource ())) {System.out.println ("True"); }        //Play//Player.play ();    }}

After running, we find the output "true", which shows what the situation is, we are in the CDPlayer () and Othercdplayer () method when invoking the CDPlayer (Cdsource ()) construct, by Cdsource () Gets the music resource object is the same, by default, the Bean in spring is singleton, spring intercepts the call to Cdsource (), and ensures that the spring-created Bean is returned, that is, spring itself calls Cdsource the first time ( ) created by the Bean.

Spring Learning Series (iii) assembling beans through Java code

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.