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;
}