A detailed description of spring's various annotation labels

Source: Internet
Author: User

Annotations such as @Autowired and @resource inject beans from the spring container into properties, while annotations such as @component are managed in the spring container.

@Autowired

spring2.1 allows the user to annotate the bean's attribute variables through @autowired annotations. The property setter method and the constructor are annotated, and the bean's automatic configuration is done with the autowiredannotationbeanprocessor. Use @autowired annotations for Bytype injection.

Add in Applicationcontext.xml:

[XML]View PlainCopy
    1. <!--the beanpostprocessor will automatically inject the Bean labeled @Autowired-
    2. <Bean class="Org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />

Use the @Autowired to eliminate the set, get method.

[XML]View PlainCopy
    1. @Autowired
    2. Private Userdao Userdao;

This allows you to delete the set, the Get method, and the related configuration in spring.

[Java]View PlainCopy
    1. <bean id="Userdao" class="..."/>
    2. <bean id="UserService" class="..." >
    3. <property name="Userdao" >
    4. <ref bean="Userdao"/>
    5. </property>
    6. </bean>

Injects a value into a property in the parent class through the setter method of the @autowired genus.

[Java]View PlainCopy
    1. @Autowired
    2. Public void Setdatasource (DataSource DataSource)
    3. {
    4. Super.setdatasource (DataSource);
    5. }
@Autowired (required = false)

When it is not possible to determine the bean that must have a class in the Spring container, you can use the @Autowired (required = false) where it is necessary to automatically inject the class bean, which is tantamount to telling Spring that there is no error when a matching Bean is found.

Of course, in general, the use of @Autowired place is the need to inject beans, using automatic injection and allow non-injection is generally only encountered during the development period or test period (such as to quickly start the spring container, only a few modules of the spring configuration file), so @ Autowired (required = false) is seldom used.

@Qualifier

Use the @autowired annotation for Bytype injection, and add @qualifier comments if you need to inject byname (ByName is identified by ID). It is common to add @qualifier comments when the number of candidate beans is not 1.

When automatic injection is made using @Autowired annotations by default, the number of candidate beans that match in the Spring container must be and only one. When a matching Bean is not found, the Spring container throws

Beancreationexception the exception and indicates that at least one matching Bean must be owned.

And there is no one type matching Bean the opposite error is: If the Spring container has more than one candidate bean,spring container at startup will also throw a beancreationexception exception.

Spring allows us to specify the name of the injected Bean by @Qualifier comment, so the ambiguity is eliminated, and the exception can be resolved in the following way:

[Java]View PlainCopy
    1. @Autowired
    2. Public void Setoffice (@Qualifier ("office") office Office)
    3. {
    4. This.office =office;
    5. }

You can also inject directly into a property:

[Java]View PlainCopy
    1. @Autowired
    2. @Qualifier ("office")
    3. Private Office Office;

Office in @Qualifier ("office") is the name of the bean, so when @autowired and @qualifier are used together, the auto-injected strategy is transformed from Bytype to ByName.

@Autowired can comment on member variables, methods, and constructors, while @qualifier's label objects are member variables, method entry parameters, constructor arguments. Because of the different annotation objects, spring does not unify the @Autowired and @qualifier into a single annotation class.

@Qualifier can only be used in conjunction with @autowired, which is a useful supplement to @autowired.

In general, @Qualifier commenting on the parameters of a method signature reduces the readability of the code, while the comment on the member variable is relatively good.

@Resource

Spring not only supports its own defined @autowired annotations, it also supports several annotations defined by the JSR-250 specification, namely @resource, @PostConstruct, and @predestroy.

The function of the @Resource is equivalent to @autowired, but @autowired is automatically injected by Bytype, and @resource is automatically injected by ByName by default. @Resource There are two attributes that are important, the name and type,spring the Name property of the @resource annotation to the bean's name, and the type attribute to the Bean's. So if you use the Name property, you use the ByName Auto-injection policy, and the Type property uses the Bytype auto-injection policy. If neither name nor the type attribute is specified, the ByName auto-injection policy is used through the reflection mechanism.

@Resource Assembly Order

1. If name and type are specified at the same time, the uniquely matched bean is found from the spring context to assemble, and an exception is thrown if it is not found

2. If name is specified, a bean matching the name (ID) from the context is assembled, and an exception is thrown if it is not found

3. If the type is specified, an exception is thrown when the unique bean matching the match is found in the context, cannot be found, or multiple occurrences are found

4. If neither name is specified and type is not specified, the assembly is automatically byname; if there is no match, the fallback is a match for the original type, and if the match is automatically assembled;

@Component, @Repository, @Service, @Controller

In addition to providing @Component annotations in Spring 2.5, several annotations with special semantics are defined, namely, @Repository, @Service, and @Controller.

In the current Spring version, these 3 comments and @Component are equivalent, but from the name of the annotation class it is easy to see that the 3 annotations correspond to the persistence layer, the business layer, and the control layer (the WEB layer), respectively.

Although there is nothing new about these 3 annotations and @Component, Spring will add special features to them in future releases.

Therefore, if a WEB application uses a classic three-tier hierarchy, it is best to annotate the classes in the hierarchy with the above annotations, respectively, in the persistence layer, the business layer, and the control layer.

@Service for labeling business layer components

@Controller for labeling control-layer components, such as action in struts

@Repository for labeling data Access Components, DAO components

@Component refer to components, we can use this annotation when the component is poorly categorized.

[Java]View PlainCopy
    1. @Service
    2. Public class Ventorserviceimpl implements Iventorservice {
    3. }
    4. @Repository
    5. Public class Ventordaoimpl implements Iventordao {
    6. }

In a slightly larger project, if the component is configured with an XML bean definition, it will obviously increase the volume of the configuration file, and it may not be easy to find and maintain.

SPRING2.5 introduced the component automatic scanning mechanism, where he looked for classes labeled the above annotations in the classpath and managed them into the spring container.

its role is the same as when you configure a component with a bean node in an XML file. to use the automatic scanning mechanism, we need to open the following configuration information:

[XML]View PlainCopy
  1. <? XML version= "1.0" encoding="UTF-8" ?>
  2. <beans xmlns="Http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="Http://www.springframework.org/schema/context"
  5. xsi:schemalocation= "Http://www.springframework.org/schema/beans
  6. Http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  7. Http://www.springframework.org/schema/context
  8. Http://www.springframework.org/schema/context/spring-context-2.5.xsd ">
  9. <context:annotation-config />
  10. <context:component-scan base-package= "com.iteedu.spring">
  11. </Beans>

Annotation-config is @Required, @Autowired, @PostConstruct, @PreDestroy, @Resource, @WebServiceRef, @EJB, @ Persistencecontext, @PersistenceUnit, and other annotated classes do the same to make the annotations effective.

The Base-package is a package that needs to be scanned (including all child packages) and is responsible for scanning classes that have @Component,@Repository, @Service, and @Controller annotations.

You can specify the initialization method and the destruction method in the following ways:

[Java]View PlainCopy
      1. @PostConstruct
      2. Public void Init () {
      3. }
      4. @PreDestroy
      5. Public void Destory () {
      6. }

A detailed description of spring's various annotation labels

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.