Spring注解 @Resource和@Autowired比较

先看源码注释

/**Autowired
 * Marks a constructor, field, setter method or config method as to be
 * autowired by Spring's dependency injection facilities.
 */
/**Resource 
 * The Resource annotation marks a resource that is needed
 * by the application.  This annotation may be applied to an
 * application component class, or to fields or methods of the
 * component class.  */

1.相同:

都可以标记fields、method

都用来注入bean

2.不同

Autowired:

1)由spring提供,需要import org.springframework.beans.factory.annotation.Autowired

2)依据bean类型匹配注入

3)具有required属性,默认required=true,这样必须有且仅有一个该类型的bean对象.如果设置required=false,则该类型bean对象可以为null

4)如果想使用名称来装配,可以结合@Qualifier注解一起使用。如:@Qualifier("xxx")


Resource :

1)由java提供,需要import javax.annotation.Resource

2)默认依据bean 名称匹配注入

3)具有name、type重要属性,使用方法如下:

如果同时指定name和type属性,这样必须有且仅有一个该名称、该类型的bean对象,否则抛出异常。

如果只指定name(@Resource(name="xxx"))属性,则必须有一个id="xxx"的bean,否则抛出异常。

如果指定了type属性,这样必须有且仅有一个该类型的bean对象,否则抛出异常。

如果name、type属性都没有指定,则spring会按照name=field值查找bean;如果没有找到,则按类型进行查找;如果没有找到,抛出异常

4)另外还有authenticationType、shareable、mappedName、description属性,用的比较少,这里不详细讲解。



发布了33 篇原创文章 · 获赞 2 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/zjj2006/article/details/53117016