3

java | @Resource

 1 year ago
source link: https://benpaodewoniu.github.io/2022/11/17/spring17/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

这个要和 @Autowired 一起看。

@Resource 是JDK原生的注解。

@Resource有两个属性name和type。

Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。

所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。

如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略。

@Autowired只根据type进行注入,不会去匹配name。如果涉及到type无法辨别注入对象时,那需要依赖@Qualifier或@Primary注解一起来修饰。

定义接口做饭Cook.java

public interface Cook {
String cooking();
}

定义实现类炒西红柿CookTomato.java

@Service
public class CookTomato implements Cook {
@override
public String cooking() {
return "炒西红柿中~";
}
}

定义Controller类CookController.java,注入Cook接口

@RestController
@RequestMapping("/cook")
public class CookController {

@Resource
private Cook cook;

@RequestMapping("/cooking")
public String cooking() {
return cook.cooking();
}
}

启动Spring Boot运行起来后请求三个接口都是正常的返回结果。

但是如果我们增加Cook接口的实现类

@Service
public class CookPatato implements Cook {
@override
public String cooking() {
return "炒土豆丝中~";
}
}

这个时候启动Spring Boot,控制台会报错

2021-10-24 10:24:10.662  WARN 5592 --- [  restartedMain] 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,CookPatato

大致意思是我们引入Cook但是Spring框架发现了有两个实现,无法匹配到bean
我们将代码改成这样

@Resource(name="cookTomato")
private Cook cook;
@Resource
@Qualifier("cookTomato")
private Cook cook;

就可以了。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK