Correctly distinguish the difference between @Autowire and @Resource annotations

Everyone knows that these two annotations can achieve bean injection

@Autowired This is spring's annotation org.springframework.beans.factory.annotation.Autowired

@Resource This belongs to the annotation javax.annotation.Resource that comes with java

 

@Autowired is injected by type by default, and dependent objects must exist by default.

  • If you allow the dependent object to be null, you need to set the required attribute to false,

If you need to inject by name, you can use it with @Qualifier

@Resource is injected according to the name attribute inside

  • If name is not specified
  1. When the annotation is on the field, name=field name assembly is taken by default.
  2. When the annotation is on the setter method, name=property name assembly is taken by default.
  • When assembling by name (by-name) does not match, assembling by type (by-type).
  1. When the specified name attribute is displayed, it can only be assembled by name (by-name).

@Resoure assembly sequence

  1. If the name and type attributes are specified at the same time, the only matching bean assembly will be found, and an exception will be thrown if it is not found;
  2. If the name attribute is specified, it will be assembled according to the name (by-name), and an exception will be thrown if it is not found;
  3. If the type attribute is specified, it will be assembled according to the type (by-type), and an exception will be thrown if it is not found or if more than one is found;
  4. If neither the name attribute nor the type attribute is specified, it will be assembled according to the name (by-name); if it is not found, it will be assembled according to the type (by-type).

Compare

Comparison item @Autowire @Resource
Annotation source Spring annotation JDK annotations (JSR-250 standard annotations, belonging to J2EE)
Assembly method Priority by type Priority by name
Attributes required name、type
Scope of action Fields, setter methods, constructors Field, setter method

@Resource is recommended

  • Annotations belong to J2EE, reduce coupling with Spring

Guess you like

Origin blog.csdn.net/qq_27828675/article/details/109348063