@Autowired and @Resource of Spring

@Autowired is a spring annotation, org.springframework.beans.factory.annotation.Autowired

 @Resource is not a Spring annotation, the annotation supported by jdk1.6 javax.annotation.Resource

Common ground:

     Equip beans, write on fields, or write in setter methods

difference:

     @Autowired default equipment by type

           The dependent object must exist. If null values ​​are allowed, you can set its required property to false @Autowired (required = false)

You can also use the name assembly, with @Qualifire annotation

 

to sum up:

  @Autowired Automatic annotation, for example, one class, two implementation classes, @Autowired does not know which implementation class to inject, and Resource has a name attribute

Can be distinguished

 

1. Both @Autowired and @Resource can be used for assembling beans. Both can be written on fields or setter methods.

2. @Autowired is assembled by type by default (this annotation belongs to the industry spring). By default, the dependent object must exist. If you want to allow null values, you can set its required property to false, such as: @Autowired (required = false), if we want to use name assembly we can use it in conjunction with @Qualifier annotation, as follows:

 

 

3. @Resource (this annotation belongs to J2EE), the default is to assemble according to the name, the name can be specified by the name attribute, if the name attribute is not specified, when the annotation is written on the field, the field name is taken by default for the installation name search, if The annotation is written on the setter method by default to take the attribute name for assembly. When no bean matching the name is found, it is assembled according to the type. However, it should be noted that if the name attribute is specified, it will only be assembled according to the name.

 

 

 

Guess you like

Origin www.cnblogs.com/weigy/p/12729914.html