共同点:都可以起到注入属性的作用,当接口只有单一的实现类时,可以相互替换,效果是相同的。
## @Resource@Resource是JDK原生的注解。
@Resource有两个属性 name 和 type。如果在不指定属性的情况下,默认使用 byName 的方式自动注入策略。如果使用 name 属性,则使用 byName 的自动注入策略,而使用 type 属性时则使用 byType 自动注入策略。
public interface Cook {
String open();
}
@Service
public class CookTomato implements Cook {
@override
public String open() {
return "炒西红柿前打开油烟机并开火";
}
}
@RestController
@RequestMapping("/cook")
public class CookController {
@Resource
private Cook cook;
@RequestMapping("/open")
public String open() {
return cook.open();
}
这个时候SpringBoot是可以正常启动的,但是如果我们增加了 Cook 接口的实现类
@Service
public class CookFish implements Cook {
@override
public String open() {
return "煮鱼前打开油烟机并开火";
}
}
会发现 SpringBoot 是会报错的
ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'CookController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.janeroad.annotation.service.Cook' available: expected single matching bean but found 2: CookTomato,CookFish
当我们指定了 name 属性,SpringBoot启动的时候就知道去注入哪个
@Resource(name="cookTomato") private Cook cook;
或者
@Resource
@Qualifier("cookTomato")
private Cook cook;
@Autowired
@Autowired是Spring2.5 引入的注解
@Autowired只根据 type 进行注入。如果涉及到type无法辨别注入对象时,那需要依赖 @Qualifier 或 @Primary 注解一起来修饰。
其中 @Qualifier 的方式跟 @Resource 结合的方式是一样的,而 @Primary 是告诉Spring,如果有多个实现类时,优先注入被@Primary注解修饰的那个。



