@Resource and @Autowired comparison

Same point

Annotate fields or methods to achieve automatic assembly

difference

1. @Autowired is provided by spring, @Resource is provided by java language, using this annotation can achieve decoupling of spring (but now it is the world of spring, which is of little significance)

2. Different ways to find beans

@Autowired : First find the bean by type. If one is found, it will be injected directly. If it is not found, an exception will be thrown. If multiple beans are found, an exception will also be thrown. Solution 1: You can add it when configuring the bean Use the @Primary annotation to increase the priority so that no error will be reported. Solution 2: The field name will be used to match by default. If there is no match, an exception will be thrown. If you need to find it directly by the id of the bean, you can use it with @Qualifier. If no exception is found, it will be thrown.

PS: It is important to point out that the use of @Autowired has priority, @Qualifier> find by type (if you find multiple strategies after continuing to use)> @Primary> find by name

@Resource:  If the name attribute is set in the annotation, it is directly searched by id, if not, an exception is thrown; if the name attribute is not set in the annotation, the default is to search through the field name (or parameter name) first, and if it is not found, then pass Type search. If 0 or more are found, an exception will be thrown. Note: @Primary is not supported here to solve the situation where multiple beans are found for one type.

3. @Autowired will not throw an exception if no bean is found by setting required=false

In summary, @Autowired has more functions and is recommended

Guess you like

Origin blog.csdn.net/qq_28411869/article/details/89355153