gpt4 book ai didi

spring - Autowire Spring bean 实现两个接口(interface)

转载 作者:行者123 更新时间:2023-12-02 01:11:09 25 4
gpt4 key购买 nike

是否可以让 Spring Bean 实现 2 个接口(interface)并能够使用任一接口(interface) Autowiring 该 Bean?

我有以下两个接口(interface):

public interface ServiceA {}

public interface ServiceB {}

两个 Controller 使用构造函数 Autowiring 来注入(inject)不同的服务:

@RestController
public class ControllerA {

public ControllerA(ServiceA service) {}

}

@RestController
public class ControllerB {

public ControllerB(ServiceB service) {}

}

一个类实现这两种服务

@Service
public class ServiceImpl implements ServiceA, ServiceB { }

我收到一个NoSuchBeanDefinitionException:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [ServiceB] found for dependency [ServiceB]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}

我使用的是 Spring Boot 版本 1.4.0

最佳答案

是的,这是可能的,但是重要的是,创建 ServiceImpl 类型的服务 bean,而不是作为服务接口(interface)之一:

@Bean
ServiceImpl service() {
return new Serviceimpl();
}

Spring 在声明的 bean 类型上使用反射来找出它实现的接口(interface),而不是在 bean.getClass() 上。

即使这个答案被投票为 dowen,您也可以放心:它有效。如果它对你不起作用@scarba05,你的问题一定在其他地方......

关于spring - Autowire Spring bean 实现两个接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39919965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com