[Spring] difference between Autowired principle and Resource annotation, springautowired

Source: Internet
Author: User

[Spring] difference between Autowired principle and Resource annotation, springautowired
Autowired Annotation

Autowired, as its name implies, indicates automatic injection. The source code of the Autowired annotation is as follows:

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Autowired {    /**     * Declares whether the annotated dependency is required.     * <p>Defaults to {@code true}.     */    boolean required() default true;}

We can see from the implementation of Autowired that Autowired can be used for class constructor methods, class fields, class methods and annotation types, but Autowired cannot be used for classes.

The Autowired annotation has the following problems to solve:

1. What is the Assembly policy of Autowired in different scopes (constructor, field, and method), by name or type?

2. For the construction method, after the Autowired annotation is added to the fields and methods, who will parse the Autowired annotation to complete the assembly?

3. Where does the assembled bean come from? Is it the bean defined in the Spring xml file?

Starting from javadoc of Autowired

Obtain the following information from javadoc of Autowired:

1. AutowiredAnnotationBeanPostProcessor is responsible for scanning Autowired annotations and then completing automatic injection.

2. You can use Autowired to automatically assemble private fields without defining getter/setter for read/write fields.

3. the class method annotated with Autowired can be any method name and any parameter. Spring will find the appropriate bean from the container for assembly. The effect of setter automatic injection is the same as that of automatic field injection.

Autowired annotation Parsing

When the Autowired annotation is used in the project, you must explicitly inform Spring that the automatic injection function is referenced in the configuration. There are two methods to use the Spring configuration file:

1. Configure AutowiredAnnotationBeanPostProcessor

2. Use <context: annotation-config/>. <Context: annotationconfig/> is implicitly registered with the Spring container.AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor,PersistenceAnnotationBeanPostProcessorAndequiredAnnotationBeanPostProcessorThe four BeanPostProcessor.

 

Instance 1. instance 1:
  • The UserDao on which UserSerice depends uses the Autowired annotation,

  • UserDao is not defined in the Spring configuration file

Result: UserDao is null.

 

2. Example 2:
  • UserSerice depends on UserDao using Autowired Annotation

  • UserDao is defined in the Spring configuration file

Result: UserDao is null.

 

3. Example 3:
  • UserSerice depends on UserDao using Autowired Annotation

  • UserDao is defined in the Spring configuration file

  • Use <context: annotation-config/> in Spring

Result: UserDao is injected correctly, and the implementation of UserDao configured in Spring is the interface of UserDao in UserService. That is to say, although their types are not completely matched

Link, Spring can still complete automatic Injection

 

4. Example 4:
  • UserSerice depends on UserDao using Autowired Annotation

  • UserDao is defined in the Spring configuration file

  • Configure AutowiredAnnotationBeanPostProcessor in Spring

Result: UserDao is correctly injected, same as instance 3.

 

5. Example 5:
  • UserSerice depends on UserDao using Autowired Annotation

  • UserDao has two definitions in the Spring configuration file (different IDs)

  • Use <context: annotation-config/> in Spring

Result:

1.If the property name of UserDao is the same as the id of a bean, it is automatically assembled according to the matching principle of property name and id name.

2. If the UserDao attribute name defined in UserService is different from the two IDs in the Spring configuration file, the injection fails and an exception is thrown, prompting that automatic assembly cannot be completed.

 

Conclusion:

1. To use Autowired for automatic assembly, you must use <context: annotation-config/> In the Spring configuration file to tell Spring that automatic assembly scanning is required (AutowiredAnnotationBeanPostProcessor is not recommended)

2. autowired matches by type by default. When multiple matching beans meet the condition, the matching is performed based on the attribute name and bean id, if there are still multiple matches or none, an exception is thrown, prompting automatic assembly failure.

3. When using Autowired, you can use the Qualifier annotation to explicitly specify the bean corresponding to the id when a conflict occurs.

4. the Autowired annotation automatic assembly function completes automatic injection of dependencies. Therefore, in a bean, the bean it depends on can be automatically injected without explicitly injecting its attributes. However, these dependent beans cannot be omitted. You still need to configure them in Spring. Instead, you only need to omit the bean attribute injection configuration code.

 

Resource Annotation

Resource annotation is equivalent to Autowried + Qualifier annotation in terms of functionality and purpose. Resource annotation is part of the JSR-250 specification and is defined in JDK's javax. annoation package as follows:

package javax.annotation;import java.lang.annotation.*;import static java.lang.annotation.ElementType.*;import static java.lang.annotation.RetentionPolicy.*;/** * The Resource annotation marks a resource that is needed * by the application.  This annotation may be applied to an * application component class, or to fields or methods of the * component class.  When the annotation is applied to a * field or method, the container will inject an instance * of the requested resource into the application component * when the component is initialized.  If the annotation is * applied to the component class, the annotation declares a * resource that the application will look up at runtime. <p> * * Even though this annotation is not marked Inherited, deployment * tools are required to examine all superclasses of any component * class to discover all uses of this annotation in all superclasses. * All such annotation instances specify resources that are needed * by the application component.  Note that this annotation may * appear on private fields and methods of superclasses; the container * is required to perform injection in these cases as well. * * @since Common Annotations 1.0 */@Target({TYPE, FIELD, METHOD})@Retention(RUNTIME)public @interface Resource {    /**     * The JNDI name of the resource.  For field annotations,     * the default is the field name.  For method annotations,     * the default is the JavaBeans property name corresponding     * to the method.  For class annotations, there is no default     * and this must be specified.     */    String name() default "";    /**     * The name of the resource that the reference points to. It can     * link to any compatible resource using the global JNDI names.     *     * @since Common Annotations 1.1     */    String lookup() default "";    /**     * The Java type of the resource.  For field annotations,     * the default is the type of the field.  For method annotations,     * the default is the type of the JavaBeans property.     * For class annotations, there is no default and this must be     * specified.     */    Class<?> type() default java.lang.Object.class;    /**     * The two possible authentication types for a resource.     */    enum AuthenticationType {            CONTAINER,            APPLICATION    }    /**     * The authentication type to use for this resource.     * This may be specified for resources representing a     * connection factory of any supported type, and must     * not be specified for resources of other types.     */    AuthenticationType authenticationType() default AuthenticationType.CONTAINER;    /**     * Indicates whether this resource can be shared between     * this component and other components.     * This may be specified for resources representing a     * connection factory of any supported type, and must     * not be specified for resources of other types.     */    boolean shareable() default true;    /**     * A product specific name that this resource should be mapped to.     * The name of this resource, as defined by the <code>name</code>     * element or defaulted, is a name that is local to the application     * component using the resource.  (It's a name in the JNDI     * <code>java:comp/env</code> namespace.)  Many application servers     * provide a way to map these local names to names of resources     * known to the application server.  This mapped name is often a     * <i>global</i> JNDI name, but may be a name of any form. <p>     *     * Application servers are not required to support any particular     * form or type of mapped name, nor the ability to use mapped names.     * The mapped name is product-dependent and often installation-dependent.     * No use of a mapped name is portable.     */    String mappedName() default "";    /**     * Description of this resource.  The description is expected     * to be in the default language of the system on which the     * application is deployed.  The description can be presented     * to the Deployer to help in choosing the correct resource.     */    String description() default "";}

The Autowried annotation first matches according to the type. If there are multiple types matching, it matches according to the attribute name and bean id (the Qualifier annotation can force match the specified bean id ). Resource annotations have different order, and there are several possible situations:

 

  • The Resource annotation specifies the name and type attributes.

Policy: first, perform the name-based matching policy: match the name attribute and bean id. If yes, determine whether the searched bean is of the type specified by the type attribute, if it is the type specified by the type attribute, the match is successful. If notType specified by the type attribute, Then an exception is thrown.If the name attribute does not match the bean id, an exception is thrown and the bean id does not match the name attribute.

 

  • The name attribute is specified in the Resource annotation, And the type attribute is not specified.

Policy: query the bean whose id is the name attribute. If the bean is found and does not care about the type, the matching is successful. If the bean id specified by the name attribute is not found, the matching fails and an exception is thrown.

 

  • The type attribute is specified in the Resource annotation, and the name attribute is not specified.

Policy: first, perform the name-based matching policy: match the property name and bean id. If yes, determine whether the searched bean is of the type specified by the type attribute. If yes, the match is successful. If notType specified by the type attribute, Then an exception is thrown.The system prompts that the matching fails. Second, the matching policy is performed based on the type. If the attribute name does not match the bean id, the system searches for the bean with the type. If only one is found, the system automatically assembles the bean, otherwise, it fails.

 

  • The type and name attributes are not specified in the Resource annotation.

 Policy:First, the policy is matched by the attribute name, and the injection is successful if the attribute name does not match. If the attribute name does not match, the type matching policy is applied. Only one type matching policy is successful. Otherwise, the policy fails.

 

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.