@Autowire 和 @Resource 的区别是什么?

Spring内置的@Autowire和JDK内置的@Resource和@Inject都是可以用来注入Bean对象的。而在这三个里面,@Autowire和@Resource是用的最多的。

@Autowire属于Spring内置的注解,默认的注入方式是byType(根据类型进行匹配),也就是说会优先根据接口类型去匹配并注入Bean(接口的实现类)。

但是会有一个问题,就是当一个接口有多个实现类的时候,byType这种方式就无法正确的注入对象了,因为这个时候Spring会同时找到多个满足条件的选择,默认情况下,他不知道要选择具体的哪一个实现类作为Bean。

这种情况下,注入方式会变成byName(根据名称进行匹配),这个名称通常就是类名(首字母小写),如下:
@Autowire
private StudentService studentService;//studentService 就是我所说的名称。
若现在一个接口StudentService被多个实现类实现,比如:StudentServiceImpl_1实现和StudentServiceImpl_2实现,那么在注入的时候就需要作出改变,如下:
//错误的注入方式,现在不知道具体调用哪一个实现类。
@Autowire
private StudentService studentService;

//正确的注入方式,可以通过指定具体的实现类名称进行注入。
@Autowire
private StudentService StudentServiceImpl_1;

//正确的注入方式,可以使用@Qualifier(value = "StudentServiceImpl_2")
//更加推荐这一种方式。
@Autowire
@Qualifier(value = "StudentServiceImpl_2")
private StudentService studentService;
@Resource有两个比较重要并且日常开发常用的属性:name(名称)、type(类型)
@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
public @interface Resource {
    String name() default "";
    Class<?> type() default java.lang.Object.class;
}
如果仅仅指定name属性则注入方式为byName,如果仅仅指定type属性则注入的方式为byType,如果同时指定name+type属性,则注入方式为:byName+byType
//错误的注入方式,现在不知道具体调用哪一个实现类。
@Resource
private StudentService studentService;

//正确的注入方式,可以通过指定具体的实现类名称进行注入。
@Resource
private StudentService StudentServiceImpl_1;

//正确的注入方式,可以使用@Resource(name = "StudentServiceImpl_2")
//更加推荐这一种方式。
@Resource(name = "StudentServiceImpl_2")
private StudentService studentService;

总结:

  • @Autowire是Spring提供的注解,@Resource是JDK提供的注解。

  • @Autowire默认注入方式为byType,@Resource默认的注入方式是byName

  • 当一个接口有多个实现类的时候,@Autowire和@Resource都需要通过名称进行查找匹配到具体的Bean对象,@Autowire是@Qualifier(value = ""),@Resource是使用其自身的一个name属性实现指定。

全部评论

相关推荐

不愿透露姓名的神秘牛友
06-26 15:18
点赞 评论 收藏
分享
炫哥_:哥们项目描述里面vector和mysql之类的都要写吗,直接开头技术栈巴拉巴拉就行了,完全不是技术点啊
点赞 评论 收藏
分享
“校招”、“3-5年经验”
xiaolihuam...:逆向工程不是搞外挂的吗,好像现在大学生坐牢最多的就是诈骗罪和非法侵入计算机系统罪,发美金,还居家办公,就是怕被一锅端,
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务