Difference between @Autowired and @Resource

1. Both @Autowired and @Resource can be used to assemble beans. Both can be written on fields, or on setter methods.
2. @Autowired is assembled by type by default (this annotation belongs to spring). By default, the dependent object must exist. If you want to allow null values, you can set its required property to false, such as: @Autowired(required= false) , if we want to use name assembly, we can use it in conjunction with the @Qualifier annotation, as follows:
@Autowired()
@Qualifier("baseDao")     
private BaseDao baseDao;    

3. @Resource (this annotation belongs to J2EE, which reduces the coupling with spring), the assembly is performed according to the name by default, and the name can be specified by the name attribute.
If the name attribute is not specified, when the annotation is written on the field, the default value is used. The field name is searched by name. If the annotation is written on the setter method, the attribute name is used for assembly by default. Assemble by type when no bean matching the name is found. But it should be noted that if the name attribute is specified, it will only be assembled according to the name.
Java Code Favorite Code
@Resource(name="baseDao")     
private BaseDao baseDao;  
 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326653746&siteId=291194637
Recommended