考虑下面的代码
public interface Iface1 { }
public interface Iface2 { }
public class A implements Iface1, Iface2 {
}
@Configuration
public class AutoConfig {
@Bean
Iface1 provideIface1Impl() {
return new A(); // instance no 1234
}
@Bean
@ConditionalOnBean(A.class)
@Autowired
Iface2 provideIface2Impl(A aImpl) {
return aImpl;
}
}
我希望第二个 @Bean
方法与第一个 (1234) 中的实例 Autowiring ,并且我希望第二个 @Bean
方法返回相同的实例,以便我可以为 Iface1
和 Iface2
的客户端使用相同的实例。
当前的问题是 spring 不运行第二个 @Bean
因为没有 A.class
类型的 @Bean
-创建的 bean 被视为 Iface1
,即使它的类型为 A
。
最佳答案
只需定义 bean A。当注入(inject) IFace1 和 Iface2 时,它们将自动解析为 A(当然,如果 A 是唯一的实现)。
@Bean
public A a() {
return new A();
}
关于java - 提供单个@Bean,可用于在多个接口(interface)中注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47528922/