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。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容