Note of Spring (ii) autowired

Source: Internet
Author: User

Starting with Spring 2.0, Spring adds support for annotation-type metadata configurations in turn. Since then we have another way of configuring beans. In the previous article, we made a general classification of the annotations supported by spring and gave a preliminary introduction to them. In this article, it is described in more detail. It mainly covers the level of dependency, and some attribute levels are interspersed with the process.

The example code used in this article inherits the previous chapter.

Dependency level

Spring can use these annotations for dependency injection, usually automatically, or with some ancillary information. That is to say, our definition of beans is in the way of XML, and the injection that relies on it uses annotations.

@Autowired

The first appearances of course are Daming Dingding's @autowired. From the name you can see that it can "automatically assemble dependencies." It first adds the following configuration to the configuration file by type auto-injection (bytype), @Autowired effective:

<bean   class= "Org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

@Autowired can be labeled on the field, set methods and constructors, if we say that we have the following configuration in order, and already in the XML file has a bean definition, the following three ways equivalent, are automatically injected on the dependency Userdao, and the previous article can use XML Injection-dependent way of comparison:

Label on the field.   @Autowired   private Userdao Userdao;

Label on the set method.   @Autowired public   void Setuserdao (Userdao userdao) {      This.userdao = Userdao;   }

Label on the constructor   @Autowired public   UserServiceIml3 (Userdao Userdao) {      super ();      This.userdao = Userdao;   }  


In XML, the bean is defined as follows:

<bean id= "user1" class= "Com.test.service.UserServiceIml1"/> <bean id= "user2" class= " Com.test.service.UserServiceIml2 "/> <bean id=" User3 "class=" COM.TEST.SERVICE.USERSERVICEIML3 "/>

The above injection is our own definition of the interface, of course, can also inject some of the spring core interface, such as ApplicationContext, as follows:

@Autowired    private ApplicationContext context;

In addition, @resource is the annotation of JSR-250, which has the same meaning as @Autowired , but with limitations, to make it effective, you need to declare the corresponding beanpostprocessor in the bean definition file:

Can be used in the field and only one parameter of the Set method, meaning equal @autowired   @Resource   private Userdao Userdao;

<bean class= "Org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/


Another JSR-330 annotation @Inject and the role of @Autowired basically the same, this is not mentioned here.

@Qualifier

@Autowired use Bytype for dependency injection, there may be multiple matches (such as we have two userdao beans in the spring container), then this time throws an exception, so we need more granular control, which is @qualifier Place to debut. @Qualifier can use the field, method parameters, to limit the aotowired candidate Bean from "first name". In general, you can use the bean's name directly as the value of the @qualifier to restrict the injection of the specified bean. Of course you can also use the <Qualifier> tag in XML, so the benefit is that the value of Qualifier can be not unique.

If we have two Userdao, namely Userdao and userDao1, then we need to change the above configuration as follows:

Callout on the constructor   @Autowired public   UserServiceIml3 (@Qualifier ("UserDao1") Userdao Userdao) {      super ();      This.userdao = Userdao;   }
Label on the field.   @Autowired   @Qualifier ("Userdao")   private Userdao Userdao;

The rest of the remainder is slightly.

You can also use tags to define qualifier :

<bean id= "Userdao" class= "com.test.dao.UserDaoImp" >        <qualifier value= "main"/>    </bean>

Custom @qualifier

We can customize annotations as long as you use the @qualifier callout. As follows:

@Target ({elementtype.field,elementtype.parameter}) @Retention (retentionpolicy.runtime) @Qualifierpublic @ Interface Myqualify {  String value ();}


Then we can make use of our custom annotations to implement and @qualifier the same functionality. In code and in XML, use the following sequence:

@Autowired   @MyQualify ("Usermy")   private Userdao Userdao;
<bean id= "UserDao1" class= "com.test.dao.UserDaoImp" >        <qualifier type= "Com.test.service.Myqualify" Value= "Usermy"/>    </bean>

@value

Used to automatically assemble basic types (such as int, etc.), can be used in conjunction with Springel, and can be injected into the Properties property file and constant values.

Inject the values or constants defined by the properties file as follows:

Package com.test.service; Import Org.springframework.beans.factory.annotation.Value;  public class TestValue {    @Value ("${a}")   private int A;   @Value ("${b}")   private String B;   @Value ("${c}")   private Boolean C;    private double D;         /**    * Properties Definition *    /   @Value ("${d}") Public   void setd (double d) {      this.d = D;   }     /**    * Inject constant    *   /@Value ("I am Const")   private String E;       @Override public   String toString () {      return "TestValue [a=" + A + ", b=" + B + ", c=" + C + ", d=" + D            + ", E= "+ E +"] ";   }    }


The values of the testvalue.properties are as follows:

A=

b=

C=True

d=1.33


Finally, you need to add a read to the properties file in the XML file, do not add the appropriate namespace, as follows:

<context:property-placeholder location= "Classpath:/com/test/testvalue.properties"/>

Summarize

The above detailed description of the following spring support of the use of the level of annotations, the main introduction of @autowired and @qualifier, a simple introduction of other such as @Resource. For JSR-330 @Inject is skipped, in fact, it is the same as @autowired, but it does not have a powerful function. @Required didn't mention it.

Finally note that spring uses beanpostprocessor to handle annotations such as @autowired, so it cannot be used in custom beanpostprocessor and must be configured in an XML file.

The bean definition in this article is still declared in XML, and the next chapter will change this by using @component. Full Test code

Note of Spring (ii) autowired

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.