Difference between @ Autowired and @ Resource annotation in Spring framework, spring annotation autowired
Differences between @ Autowired and @ Resource annotations in Spring framework
In the spring framework, in addition to the use of its unique annotation, the use of JSR-250 based annotation, it includes @ PostConstruct, @ PreDestroy and @ Resource annotation.
First, let's briefly understand @ PostConstruct and @ PreDestroy. Note:
To define the installation and uninstallation of a bean, we can use the init-method and destroy-method parameters to make a simple declaration. The init-method attribute specifies a method, this method is called immediately during bean instantiation. Similarly, destroy-method specifies a method that is called only before a bean is deleted from the container.
Therefore, we can use the @ PostConstruct annotation as an alternative to the initialization callback function, and use the @ PreDestroy annotation as an alternative to the destroy callback function.
Next, let's focus on @ Resource and the difference between it and Spring's unique @ Autowired annotation.
Annotation @ Resource is equivalent to @ Autowired, but @ Autowired is automatically injected by byType, while @ Resource is automatically injected by byName by default. @ Resource has two attributes, namely name and type. Spring resolves the name attribute of @ Resource annotation to the bean name, And the type attribute to the bean type. Therefore, if the name attribute is used, the automatic injection policy of byName is used, and the automatic injection policy of byType is used when the type attribute is used. If neither name nor type is specified, the byName automatic injection policy is used through reflection.
Annotation @ Resource assembly sequence:
1. If both name and type are specified, a unique matching bean is found in the Spring context for assembly. If no matching bean is found, an exception is thrown;
2. if the name is specified, the bean with the matching name (id) is searched in the context for assembly. If no name is found, an exception is thrown;
3. If type is specified, an exception will be thrown if a unique bean of type matching is found in the context for assembly and no or multiple beans can be found;
4. if neither name nor type is specified, the Assembly is automatically performed in byName mode. If no match is found, the matching is performed in the original type. If the matching is successful, automatic Assembly.
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!