SpringBoot中的autowired注解可以修饰接口吗?
对于这个问题,从本人的经验来看,接口不能实例化,autowired的本质是从IOC容器中将实例赋值给成员变量,所以autowired自然是不能修饰接口的。
但是事实上,autowired可以修饰接口,是因为这个接口有类实现它。
请看例子:
如果仅是一个接口VideoService,在Controller中注入该注解,在启动应用的时候,会报如下的错误:
Field videoService in com.imooc.miaosha.controller.SampleController required a bean of type 'com.imooc.miaosha.service.VideoService' that could not be found.
接着如果有类实现这个接口,就不会报错。
这里引申出接口有多个实现类的注入方式,启动时会报错:
Description:
Field videoService in com.imooc.miaosha.controller.SampleController required a single bean, but 2 were found:
- videoServiceImpl: defined in file [/Users/cancan/Documents/miaosha/miaosha/target/classes/com/imooc/miaosha/service/VideoServiceImpl.class]
- videoServiceImplB: defined in file [/Users/cancan/Documents/miaosha/miaosha/target/classes/com/imooc/miaosha/service/VideoServiceImplB.class]
建议使用@Primary注解使其优先被选择,或者使用@Qualifier指定注入一个Bean。