What is the difference between autowired and resource in Java annotations?

In Java annotations, both @Autowired and @Resource are used to implement dependency injection.

1. @Autowired: @Autowired is an annotation provided by the Spring framework for automatic assembly. It finds the corresponding bean through type matching and injects it into the target variable or parameter. If there are multiple matching beans, specific beans can be specified through the @Qualifier annotation.

2. @Resource: @Resource is an annotation provided by the Java EE standard and is also used to implement dependency injection. It finds the corresponding bean according to the name matching, and injects it on the target variable or parameter. If there are multiple matching beans, you can specify the specific bean through the name attribute.

 The main differences are as follows:

- Different sources: @Autowired is an annotation provided by the Spring framework, and @Resource is an annotation provided by the Java EE standard.
- Different injection methods: @Autowired injects by type matching, @Resource injects by name matching.
- The scope of use is different: @Autowired can be used on constructors, fields, methods and parameters, and @Resource can only be used on fields and methods.
- Different optionality: @Autowired default required attribute is true, which means that the dependency marked by this annotation must exist. If the corresponding bean cannot be found, an exception will be thrown. For @Resource, the default required attribute is false, which means that the dependency marked by the annotation is not necessary. If the corresponding bean cannot be found, it will not be injected.

It should be noted that @Autowired and @Resource annotations may have different specific implementations and behaviors in different contexts, depending on the specific framework or container configuration and specification.

Guess you like

Origin blog.csdn.net/m0_62600503/article/details/131860580