@AutoWired
spring的注解,默认通过类型注入,如果存在多个实例符合要求,则根据名称注入
@Resource
java自带的注解,默认通过名称注入,如过名称不存在,则根据类型进行注入
如果一个接口有多个实现类,通过这两个注解注入的时候
使用@Resource时报这样的错误
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.example.demo.service.TestService' available: expected single matching bean but found 2: testServiceImpl1,testServiceImpl2
at org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:220) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1358) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:521) ~[spring-context-5.3.10.jar:5.3.10]
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:497) ~[spring-context-5.3.10.jar:5.3.10]
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:650) ~[spring-context-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:228) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119) ~[spring-beans-5.3.10.jar:5.3.10]
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessProperties(CommonAnnotationBeanPostProcessor.java:318) ~[spring-context-5.3.10.jar:5.3.10]
使用@AutoWired时报这样的错误
Field testService in com.example.demo.DemoApplication required a single bean, but 2 were found:
- testServiceImpl1: defined in file [D:\idea\work\demo\target\classes\com\example\demo\service\impl\TestServiceImpl1.class]
- testServiceImpl2: defined in file [D:\idea\work\demo\target\classes\com\example\demo\service\impl\TestServiceImpl2.class]
则可以这样解决
1.在@AutoWired或者@Resource时,同时使用@Qualifier("testServiceImpl1")?来指定要使用的实现类
@Autowired
@Qualifier("testServiceImpl1")
private TestService testService;
@Resource
@Qualifier("testServiceImpl1")
private TestService testService1;
2.在实现类上方加@Primary,代表优先使用实现类
?这两种情况都可以解决上面的报错问题,如果两者同时使用,会优先取@Qualifier得结果
?
|