The difference between @Autowired and @Resource in Spring

1. Both @Autowired and @Resource are used for bean injection, both can be used to assemble beans, and both can be written on fields or 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. For example: @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), 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 field name is used to search by name by default. If The annotation is written on the setter method by default with the property name for assembly.

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.

@Resource(name="baseDao")     
private BaseDao baseDao;

Because the @Resource annotation belongs to J2EE, it reduces the coupling with spring.

 

http://bhdweb.iteye.com/blog/1663907

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326221740&siteId=291194637