概述
使用 @Resource 注解实现依赖注入
例子1
修改Controller,由于 StudentCtrl 需要调用 StudentSrvImpl,那么在 StudentCtrl 类中声明 StudentSrvImpl 类型的成员变量,并在上面使用 @Resource 注解
@RestController
public class StudentCtrl {
@Resource
private StudentSrvImpl studentService;
public StudentCtrl(){
System.out.println("StudentCtrl()构造方法");
}
@RequestMapping("/student/query")
public JsonResult query(){
studentService.query();
return new JsonResult(0,"查询成功!");
}
}
说明
@Resource 既没有指定 name 属性,又没有指定 type 属性,则按照 变量名 进行装配(注入),即:根据变量名 studentService,在spring容器中找到同名的对象,然后 装配(注入);
如果没有找到同名,则回退为 原始类型 进行匹配,如果匹配则自动装配(注入);
例子2
创建 StudentSrvImpl2 类,代码如下:
@Service
public class StudentSrvImpl2 implements IStudentService {
public StudentSrvImpl2(){
System.out.println("StudentSrvImpl222222构造方法");
}
@Override
public List<Student> query() {
System.out.println("调用 StudentSrvImpl222222 的query()方法");
return null;
}
public void save(Student student){
System.out.println("调用 StudentSrvImpl22222 的save()方法");
System.out.println(student.toString());
}
}
启动服务报错
报错如下:
'org.example.service.IStudentService' available: expected single matching bean but found 2: studentSrvImpl,studentSrvImpl2
报错原因

@Service 注解没有指定 value 属性,那么在 spring容器中的id,与类名相同,但首字母小写
@Resource 既没有指定 name 属性,又没有指定 type 属性,则按照 变量名 进行装配(注入),即:根据变量名 studentService,没有找到同名的,则回退为 原始类型 进行匹配,在spring容器中,有2个 对象 都能匹配 IStudentService 类型,spring容器不知道注入哪个对象,所以报错
解决例子2错误
修改 StudentCtrl 的成员变量,变量名改为:studentSrvImpl2 ,如下:
@RestController
public class StudentCtrl {
@Resource
private IStudentService studentSrvImpl2;
}
将注入 StudentSrvImpl2 类对象
原因

@Service 注解没有指定 value 属性,那么在 spring容器中的id,与类名相同,但首字母小写
@Resource 既没有指定 name 属性,又没有指定 type 属性,则按照 变量名 进行装配(注入),即:根据变量名 studentSrvImpl2,在spring容器中找到同名的 StudentSrvImpl2对象,然后 装配(注入);
例子3
不改变量名的方式:修改 StudentCtrl ,如下:
@RestController
public class StudentCtrl {
@Resource(name="studentSrvImpl2")
private IStudentService studentService;
}
将注入 StudentSrvImpl2 类对象
原因

@Service 注解没有指定 value 属性,那么在 spring容器中的id,与类名相同,但首字母小写
@Resource 指定 name 属性,从 spring容器中找 id同名的 对象,即:在spring容器中找到同名的 StudentSrvImpl2对象,然后 装配(注入);
例子4
当一个service接口有多个实现类时,一般在 @Service 注解加上 value 属性,在 @Resource注解加上 name 属性, 这样不会引发歧义
说明

@Service 注解指定 value 属性,那么在 spring容器中,该对象的id就是 value属性的值
@Resource 指定 name 属性,从 spring容器中找 id同名的 对象,即:在spring容器中找到同名的 StudentSrvImpl2对象,然后 装配(注入);
