Spring Learning notes-assembling with annotations

Source: Internet
Author: User

Using @autowired annotations

Starting with Spring2.5, one of the most interesting ways to assemble a spring bean is to automatically assemble the bean's properties using annotations.
Spring disables annotation assembly by default, and the simplest way to enable it is to use the <context:annotation-config> element in spring's context namespace configuration, as follows:

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"Xmlns:context= "Http://www.springframework.org/schema/context"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/con Text/spring-context-3.0.xsd ">          <Context:annotation-config/>    <!--Bean declarations here -    </Beans>

To continue our example in the previous section, in the XML file we have a two bean:falchion bean and a guanyu bean, in order to implement @autowired automatic assembly, our Setweapon () in the Guanyu class The @autowired annotation was added before the method, as follows:
Guanyu.java:

 Packagecom.moonlit.myspring;Importorg.springframework.beans.factory.annotation.Autowired; Public classGuanyuImplementsHero {Privateweapon Weapon;  Public voidperform () {System.out.println ("Guan Yu pick up his weapon.");    Weapon.attack (); }     PublicWeapon Getweapon () {returnweapon; } @Autowired Public voidSetweapon (Weapon weapon) { This. Weapon =weapon; }}

With annotation-based methods, we can not add the Autowire attribute to the Guanyu bean in the XML file.
Spring-idol Internal code:

</>  <ID= "Falchion"  class= " Com.moonlit.myspring.Falchion "  />  <ID=" Guanyu "  class=" Com.moonlit.myspring.GuanYu"/>

Not only can we use @autowired annotations to label setter methods, but we can also label any method that needs to automatically assemble bean references, for example, we renamed the Setweapon method of the Guanyu class to Pickupweapon, as follows:

 Packagecom.moonlit.myspring;Importorg.springframework.beans.factory.annotation.Autowired; Public classGuanyuImplementsHero {Privateweapon Weapon;  Public voidperform () {System.out.println ("Guan Yu pick up his weapon.");    Weapon.attack (); }     PublicWeapon Getweapon () {returnweapon; } @Autowired Public voidPickupweapon (Weapon weapon) { This. Weapon =weapon; }}

again run the test program Autowirepractice, the output is the same, because although there is no Setweapon method, But through @autowired annotations we pass the Pickupweapon method and Falchion bean to the Guanyu bean.
@Autowired annotations can even label the constructor, so we can't even write the set method:

 Package com.moonlit.myspring; Import org.springframework.beans.factory.annotation.Autowired;  Public class Implements Hero {    @Autowired    Private  weapon weapon;          Public void perform () {        System.out.println ("Guan Yu pick up his weapon.") );        Weapon.attack ();    }}

There are two limitations of @Autowired annotations:

    • No matching beans
    • Match multiple beans but there are solutions.
Optional Auto-assembly

By default, @Autowired properties have strong contract characteristics, and the attributes or parameters that they label must be assembly-able. If no beans can be assembled into the attributes or parameters marked by @autowired, automatic Assembly will fail (throwing annoying nosuchbeandefinitionexception).
The property does not have to be assembled, and the null value is acceptable. In this scenario, you can configure auto-assembly optional by setting the required property of @autowired to False. For example:

@Autowired (required=false)private weapon weapon;
The dependence of limited ambiguity

There may be multiple beans that satisfy the assembly condition, for example, where both the falchion bean and the halberd bean satisfy the conditions in the weapon attribute that is assembled into the Guanyu bean. At this point, if only with @autowired annotations will be a problem, only @autowired bamboo shrimp added @qualifier Note as follows:

@Autowired    @Qualifier ("falchion")    Private weapon weapon;

The falchion bean is loaded into the weapon.
As shown above, @Qualifier annotations will attempt to inject a bean with ID falchion.
In addition to qualifying by the Bean's ID, we can also add a qualifier property to the bean, using this qualifier property to qualify, such as:
We add a qualifier to the halberd bean with a value of "Weaponofguanyu":

<id= "Halberd"  class= "Com.moonlit.myspring.Halberd">     <value= "Weaponofguanyu"/>  </  Bean>

Then the annotations to the Guanyu class weapon class are as follows:

@Autowired    @Qualifier ("Weaponofguanyu")    Private weapon weapon;

The output is as follows:

Guan Yu pick up his weapon.halberd is attacking!!!

As you can see, the @qualifier reduces the matching range of the @autowired, and the final filter results in the Halberd bean Loading weapon attribute.
The <qualifier> element here defines the Fang (halberd) bean as the weapon used by Guan Yu (weaponogguanyu). In addition to specifying qualifier in XML, you can also use the qualifier class to label the Halberd class:

 Package com.moonlit.myspring; Import org.springframework.beans.factory.annotation.Qualifier; @Qualifier ("Weaponofguanyu")  Public class Implements Weapon {    publicvoid  attack () {        System.out.println (' halberd is Attacking!!! " );    }}

The program runs to get the same results.

Create a custom qualifier (Qualifier)

To create a custom qualifier, we need to define an annotation that uses the @qualifier annotation to act as his meta-annotation. For example, let's create a attack annotation to act as a qualifier.

 package   com.moonlit.myspring;  import   Java.lang.annotation.ElementType;  import   java.lang.annotation.Retention;  import   Java.lang.annotation.RetentionPolicy;  import   Java.lang.annotation.Target;  import   Org.springframework.beans.factory.annotation.Qualifier; @Target ({ Elementtype.field, Elementtype.parameter, Elementtype.type}) @Retention (retentionpolicy.runtime) @Qualifier  public  @interface   attack {}  

This class I used to limit is offensive weapon.
And then we'll mark it in front of the Fang. He is an offensive weapon (@attack) as follows:

 Package com.moonlit.myspring; @attack  Public class Implements Weapon {    publicvoid  attack () {        System.out.println (' halberd is Attacking!!! " );    }}

Finally, we use the @attack qualifier to qualify the weapon property of the Guanyu:

 package   com.moonlit.myspring;  import   org.springframework.beans.factory.annotation.Autowired;  public  class  Guanyu implements   Hero {@Autowired @attack 
    private   weapon weapon;  public  void   perform () {System.out.println ( "Guan Yu pick up his weapon.")        );    Weapon.attack (); }}

When spring tries to assemble the weapon property, spring shrinks all the optional weapon beans to the bean that is marked only by the @attack annotation. If there is only one weapon bean that uses @attack annotations, the bean will be assembled into the instrument attribute.
You can use more than one custom qualifier to play a further qualifying role. (for example, declaring a @defence first, using @attack and @defence together) is equivalent to a "and" effect.

Achieve standards-based automated assembly with @inject

In order to unify the programming model of the various dependency injection frameworks, JCP (Java Community Process) recently (and do not know when, should be sring actual combat English version of the third edition) released the Java Dependency Injection specification, JCP called it JSR-330, The more common term is at inject.
In the JSR-330:

    • @Inject is equivalent to @Autowired
    • @Named is equivalent to @Qualifier
    • The JSR-330 also has a @qualifier annotation

One thing to note is the text: "The key difference between spring's @qualifier and JSR-330 's @named lies in the semantic dimension. @qualifier Annotations Help us narrow the selection of the matched bean (by default with the Bean's ID), and @named identifies the selectable bean through the bean's ID. ”。
My understanding of this passage is that the relationship between the @qualifier is "with", and the @Named is "or". (I don't know if it's right, I need to test later)

Using an expression in annotations

Spring3.0 introduced @value, a new assembly annotation that lets us use annotations to assemble string-type values and base-type values, such as int, Boolean.
A property, method, or method parameter can be labeled directly by @value and passed in an expression of type string to assemble the property. For example:

@Value ("moonlit")private String song;

Here, we assemble a string type value for a property of type string. But the argument to the string type that passed in @value is just an expression--his calculation can be any type, so @value can label any type of property.
@Value can be used in conjunction with Spel. For example, rather than hard-coding a song property to a static value, use Spel to get a value from the system property:

@Value ("#{systemproperties.myfavoritesong}")private String song;

Spring Learning notes-assembling with annotations

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.