@Autowire、@Resource、@Qualifier的区别
一、简单说明
这三个注解的作用都是用来注入依赖对象
@Autowire
@Autowired
接口只能有一个实现类,通过byType
方式注入
默认情况下必须要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false,如:@Autowired(required=false)
@Resource
@Resource
接口可以有多个实现类,先通过byName
方式进行匹配,若匹配失败再通过byType
方式注入
@Qualifier
@Qualifier
接口可以有多个实现类,可以按实现类的类名
进行注入
二、场景示例
1、场景一(接口只有一个实现类)
Person接口
package com.study.annotationdemo.service;
/**
* @description Person接口
* @author zzy
* @date 2021年08月09日 16:43
*/
public interface Person {
}
StudentImpl实现类
package com.study.annotationdemo.service.impl;
import com.study.annotationdemo.service.Person;
import org.springframework.stereotype.Service;
/**
* @description Person 实现类-student
* @author zzy
* @date 2021年08月09日 16:45
*/
@Service("sImpl")
public class StudentImpl implements Person {
}
Controller
package com.study.annotationdemo.controller;
import com.study.annotationdemo.service.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import javax.annotation.Resource;
/**
* @description
* @author zzy
* @date 2021年08月09日 16:45
*/
@Controller
public class DemoController {
@Autowired
private Person person1;
@Resource(name = "sImpl") // service注解标注的名字
private Person person2;
@Qualifier("StudentImpl") // 注意是实现类的类名
private Person person3;
}
接口只有一个实现类时,三个注解都可以使用
2、场景二(接口有多个实现类)
在上面的场景的基础上再添加一个教师实现类
package com.study.annotationdemo.service.impl;
import com.study.annotationdemo.service.Person;
import org.springframework.stereotype.Service;
/**
* @description Person 实现类-teacher
* @author zzy
* @date 2021年08月09日 17:08
*/
@Service("tImpl")
public class TeacherImpl implements Person {
}
此时会发现
@Autowired
注入的对象会报错,因为@Autowired
通过byType来进行注入,这时Person接口有了多个实现类,它无法判断注入哪个。
而@Resource
和@Qualifier
仍然适用
Controller
package com.study.annotationdemo.controller;
import com.study.annotationdemo.service.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import javax.annotation.Resource;
/**
* @description
* @author zzy
* @date 2021年08月09日 16:45
*/
@Controller
public class DemoController {
// @Autowired
// private Person person1;
@Resource(name = "sImpl") // service注解标注的名字
private Person person2;
@Qualifier("StudentImpl") // 注意是实现类的类名
private Person person3;
@Resource(name = "tImpl") // service注解标注的名字
private Person person4;
@Qualifier("TeacherImpl") // 注意是实现类的类名
private Person person5;
}
可以通过名字来寻找实现类