@Autowired、@Resource和@Qualifier之间的区别

1.@Autowired默认是按照类型装配注入的,默认情况下它要求依赖对象必须存在(可以设置它required属性为false)。

2.@Resource默认是按照名称来装配注入的,只有当找不到与名称匹配的bean才会按照类型来装配注入。

3.@Qualifier当我们注入的接口有多个实现类时,我们需要使用这个注解说明具体需要注入哪个实现类。

有如以下接口:

import com.alibaba.fastjson.JSONObject;

public interface UserService {
    JSONObject getUserList();
}

第一个实现类:

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;

@Service("service")
public class UserServiceImpl implements UserService {

    @Override
    public JSONObject getUserList() {
        JSONObject obj = new JSONObject();
        obj.put("service","I'm service");
        return obj;
    }
}

第二个实现类:

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;

@Service("service1")
public class UserServiceImpl1 implements UserService {
    @Override
    public JSONObject getUserList() {
        JSONObject obj = new JSONObject();
        obj.put("service","I'm service1");
        return obj;
    }
}

 

Controller层注入UserService:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/hello")
public class TestController {
    @Autowired
    private UserService userService;
   
}

如果不使用@Qualifier,启动时会报以下错误:

Description:

Field userService in com.spring.TestController required a single bean, but 2 were found:

- service: defined in file [C:\Users\Administrator\IdeaProjects\test0409\target\classes\com\spring\UserServiceImpl.class]

- service1: defined in file [C:\Users\Administrator\IdeaProjects\test0409\target\classes\com\spring\UserServiceImpl1.class]

Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

加上@Qualifier就好了

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/hello")
public class TestController {

    @Autowired
    @Qualifier("service")
    private UserService userService;

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值