您的位置:首页 > 编程语言 > Java开发

Spring注解 @Resource和@Autowired比较

2021-04-19 23:12 1021 查看

先看源码注释

/**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属性,用的比较少,这里不详细讲解。



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: