Differences between @ Autowired and @ resource annotations in spring framework

Time:2019-10-12

Differences between @ Autowired and @ resource annotations in spring framework

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

First, let’s briefly understand the @ postconstruct and @ predestroy annotations:

To define the installation and uninstallation of a bean, we can use init-method and destroy-method parameters to simply state that the init-method attribute specifies a method that is called immediately during the instantiation phase of the bean; similarly, destroy-method specifies a method that is called only before a bean is removed from the container.

 Therefore, we can use the @PostConstruct annotation as an alternative to initializing callback functions and the @PreDestroy annotation as an alternative to destroying callback functions.

Next, let’s focus on @Resource and its distinction from Spring’s unique @Autowire annotation.

The annotation @ resource is equivalent to @ Autowired, except that @ Autowired is automatically injected by bytype, while @ resource is automatically injected by byname by default. @ Resource has two important attributes, name and type. Spring resolves the name attribute of the @Resource annotation to the name of the bean, while the type attribute resolves to the type of the bean. Therefore, if the name attribute is used, the byname auto injection policy is used, while the bytype auto injection policy is used when the type attribute is used. If neither name nor type attribute is specified, the byName automatic injection strategy will be used through the reflection mechanism.

 Annotate the assembly sequence of @Resource:

1. If both name and type are specified, a unique matching bean is found from the Spring context for assembly and an exception is thrown if it is not found;

2. If the name is specified, the bean matching the name (id) is found from the context for assembly, and an exception is thrown if it is not found.

3. If a type is specified, the only beans matching the type are found from the context for assembly. If no or more beans are found, an exception will be thrown.

4. If neither name nor type is specified, the assembly will be done automatically in byName mode; if no match is found, it will be returned to an original type for matching, and if the match is successful, the assembly will be done automatically.

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