**
关于 @Autowired注解与@Resource注解
**
1、@Autowired
由Spring提供,只按照byType注入。
2、@Resource
由J2EE提供,@Resource默认按byName自动注入,也提供按照byType 注入。
3、使用区别
a:@Autowired与@Resource都可以用来装配bean;
b:@Autowired默认按类型装配,不支持按名称进行装配,如果想使用名称装配可以结合@Qualifier注解进行使用,@Autowired @Qualifier(“bird”) 存在多个实例配合使用。
c:@Resource,默认按照名称进行装配,名称可以通过name属性进行指定,如果没有指定name属性,当注解写在字段上时,默认取字段名进行名称查找。如果注解写在setter方法上默认取属性名进行装配。当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。
4、实例
接口定义:
public interface Fly {
String fly(String name);
}
接口实现1:
@Component(value = "bird")
public class BirdFly implements Fly {
@Override
public String fly(String name) {
return name+"在自由自在的飞!";
}
}
@Component将对象注入到IOC容器中,且指定了名称。
接口实现2:
@Component
@Primary
public class PlaneFly implements Fly {
@Override
public String fly(String name) {
return name+"在被驾驶飞!";
}
}
@Primary:自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常
调用1:
@Slf4j
@Service
public class FlyService {
@Autowired
private Fly fly;
public void flyT(){
String response= fly.fly("ceshi");
System.out.println(response);
}
}
结果:
ceshi在被驾驶飞!
调用2:
@Slf4j
@Service
public class FlyService {
@Autowired @Qualifier("bird")
private Fly fly;
public void flyT(){
String response= fly.fly("ceshi");
System.out.println(response);
}
}
结果:
ceshi在自由自在的飞!
调用3:
@Slf4j
@Service
public class FlyService {
@Resource(name = "bird")
private Fly fly;
public void flyT(){
String response= fly.fly("ceshi");
System.out.println(response);
}
}
结果:
ceshi在自由自在的飞!