The difference between spring annotation @Autowired and @Resource

1. Both @Autowired and @Resource can be used to inject beans. Both can be written on fields (member variables), or on setter methods.
2. @Autowired is injected according to the 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 injection, we can use it in conjunction with the @Qualifier annotation.
3. @Resource (this annotation belongs to J2EE), the default is injected according to the name, the name can be specified by the name attribute, if the name attribute is not specified, if the annotation is written on the field (member variable), the field (member variable) is taken by default ) name for name lookup, if the annotation is written on the setter method, the property name is used for annotation by default. Assemble by type when no bean matching the name is found. It should be noted that if the name attribute is specified, it will only be injected according to the name.

Recommended use: @Resource is annotated on fields (member variables), so that you don't need to write setter methods, and this annotation belongs to J2EE, reducing the coupling with spring.

Off topic:

The role of @Resource is equivalent to @Autowired, except that @Autowired is automatically injected according to byType, while @Resource is automatically injected according to byName by default. @Resource has two important attributes, namely name and type. Spring parses the name attribute of the @Resource annotation into the name of the bean, and the type attribute parses it into the type of the bean. So if the name attribute is used, the automatic injection strategy of byName is used, and the automatic injection strategy of byType is used when the type attribute is used. If neither the name nor the type attribute is specified, the strategy will be automatically injected using byName through the reflection mechanism.
@Resource assembly order
1. If name and type are specified at the same time, the only matching bean will be found from the spring context for assembly, and an exception will be thrown if not found;
2. If name is specified, the name (id) will be searched from the context. ) matching bean for assembly, if not found, an exception will be thrown;
3. If type is specified, the only bean matching the type will be found from the context for assembly, if not found or more than one, an exception will be thrown;
4. If neither name nor type is specified, it will be assembled automatically according to the byName method; if there is no match, it will fall back to a primitive type for matching, and if it matches, it will be automatically assembled.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326102309&siteId=291194637