Differences between @ Autowired and @ Resource annotations in the Spring framework

  • 2021-12-09 09:41:34
  • OfStack

Differences between @ Autowired and @ Resource annotations in the Spring framework

In the spring framework, in addition to its own annotations, JSR-250-based annotations are used, including @ PostConstruct, @ PreDestroy, and @ Resource annotations.

First, let's take a brief look at @ PostConstruct and @ PreDestroy annotations:

In order to define the installation and uninstallation of an bean, we can use the init-method and destroy-method parameters under simple declaration 1, where the init-method attribute specifies a method, which will be called immediately during the instantiation stage of bean; Similarly, destroy-method specifies a method that is invoked only before an bean is removed from the container.

Therefore, we can use the @ PostConstruct annotation as an alternative to initialize the callback function and the @ PreDestroy annotation as an alternative to destroy the callback function.

Next, let's focus on @ Resource and its difference from the unique @ Autowired annotation of Spring.

Annotation @ Resource is equivalent to @ Autowired, except that @ Autowired is automatically injected by pressing byType, while @ Resource is automatically injected by pressing byName by default. Two attributes of @ Resource are important, name and type. Spring resolves the name attribute of @ Resource annotation to the name of bean, while type attribute is resolved to the type of bean. Therefore, the byName auto-injection policy is used if the name attribute is used, and the byType auto-injection policy is used when the type attribute is used. If neither the name nor the type attribute is specified, the byName auto-injection policy is used through reflection mechanism.

Note @ Resource assembly sequence:

1. If name and type are specified at the same time, the only matching bean is found from the context of Spring for assembly, and an exception is thrown if it cannot be found;   

2. If name is specified, find an bean with a matching name (id) from the context for assembly, and throw an exception if it cannot be found;

3. If type is specified, only 1 bean with matching type is found from the context for assembly. If it cannot be found or multiple bean are found, an exception will be thrown;

4. If neither name nor type is specified, the assembly will be carried out automatically according to byName mode; If there is no match, it rolls back to one original type to match, and if the match is successful, it is automatically assembled.

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: