@Autowired和@Resource学习笔记

定义一个接口

public interface HelloService {
    void sayHello();
}

实现HelloService接口

@Service
public class HelloServiceImpl implements HelloService {
    @Override
    public void sayHello() {
        System.out.println("hello");
    }
}

@Service
public class Hello2ServiceImpl implements HelloService {
    @Override
    public void sayHello() {
        System.out.println("hello");
    }
}

@Resource注解

调用HelloService接口
什么都不指定的情况下默认按照name进行匹配。

     @Resource
     private HelloService helloService;

运行代码结果如下:

org.springframework.beans.factory.BeanCreationException: Error
creating bean with name ‘helloController’: Injection of resource
dependencies failed; nested exception is
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No
qualifying bean of type ‘com.example.wechat.service.HelloService’
available: expected single matching bean but found 2:
hello2ServiceImpl,helloServiceImpl

指定name:

    @Resource(name = "helloServiceImpl")
    private HelloService helloService;

    @Resource(name = "hello2ServiceImpl")
    private HelloService helloService;

指定type:

    @Resource(type = HelloServiceImpl.class)
    private HelloService helloService;
    
    @Resource(type = Hello2ServiceImpl.class)
    private HelloService helloService;

同时指定name和type

    @Resource(name = "hello2ServiceImpl", type = Hello2ServiceImpl.class)
    private HelloService helloService;

@Autowired注解

在这里插入图片描述
直接爆红。爆红提示如下:
在这里插入图片描述
根据提示代码可以改成下图所示:加上Qualifier()注解,指定需要的bean。
在这里插入图片描述
总结:一个类型有多个bean值的时候。使用@Autowired时需要与@Qualifier()注解一起使用。使用@Resource,我们可以指定他的name或者type或者同时指定name和type.这样才不会有问题。@Resource默认是按照byName进行的。@Autowired按照byType注入。@Autowired是Spring提供的。@Resource是J2EE提供的。两个都可以写在字段上就不需要写setter方法了。@Autowired还可以写在非 setter 方法,构造函数和属性上。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值