共同点:都可以起到注入属性的作用,当接口只有单一的实现类时,可以相互替换,效果是相同的。
## @Resource
@Resource是JDK原生的注解。
@Resource有两个属性 name 和 type。如果在不指定属性的情况下,默认使用 byName 的方式自动注入策略。如果使用 name 属性,则使用 byName 的自动注入策略,而使用 type 属性时则使用 byType 自动注入策略。
/**
* Service层
*/
public interface Cook {
String open();
}
/**
* Service层实现类
*/
@Service
public class CookTomato implements Cook {
@override
public String open() {
return "炒西红柿前打开油烟机并开火";
}
}
/**
* controller层
*/
@RestController
@RequestMapping("/cook")
public class CookController {
@Resource
private Cook cook;
@RequestMapping("/open")
public String open() {
return cook.open();
}
这个时候SpringBoot是可以正常启动的,但是如果我们增加了 Cook 接口的实现类
/**
* Service层实现类
*/
@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注解修饰的那个。


本文详细介绍了SpringBoot中@Resource和@Autowired注解的区别和使用场景。默认情况下,@Resource按名称(byName)注入,而@Autowired按类型(byType)注入。当存在多个实现类时,若未指定,会导致SpringBoot启动失败。解决方法是使用@Qualifier或@Primary来明确指定注入的bean。同时,文章通过示例代码展示了如何避免注入冲突。
197

被折叠的 条评论
为什么被折叠?



