The @Resource and @AutoWired annotations are both used for Bean injection, with the most obvious difference being that @AutoWired is a Spring-provided annotation. @Resource is not a Spring annotation, but Spring supports the injection of this annotation.

Here are the specific differences between the two annotations:

@Autowired

@autowired. ByType injection by default. If there are more than one of the same types, match by byName. If the bean does not match, an error is reported.

The @autowired annotation is used with the @Qualifier annotation to specify a variable name, and the @Autowired annotation will be injected as byName by default.

@Resource

@resource is automatically injected by byName by default. The @resource has two properties that are important: name and type. Spring resolves the name attribute of the @Resource annotation to the bean name, and the Type attribute to the bean type.

So if the name attribute is used, the byName auto-injection policy is used, and if the Type attribute is used, the byType auto-injection policy is used. If neither name nor type attributes are specified, the byName automatic injection policy is used through reflection.

@resource Assembly sequence:

  1. If both name and Type are specified, a unique matching bean is found from the Spring context and assembled, failing which an exception is thrown

  2. If name is specified, the bean whose name (ID) matches is searched from the context for assembly, and an exception is thrown if no bean is found

  3. If type is specified, an exception will be thrown if a unique bean whose type matches is found in the context and assembly is performed

  4. If neither name nor type is specified, byName is automatically used for assembly. If there is no match, the system backs up to a primitive type for matching. If there is a match, automatic assembly is performed. Back to primitive type (byType match)

conclusion

  1. The @autowired annotation starts byType and then byName matches

  2. The @resource annotation starts byName and then byType matches