【问题标题】:How does spring boot framework determine which bean is autowired if there are multiple implementations of the said interface如果上述接口有多个实现,spring boot框架如何确定哪个bean是自动装配的
【发布时间】:2020-07-29 22:34:58
【问题描述】:

我对 Spring Boot IoC 和 @Bean 的概念完全陌生

假设这段代码实现了

@SpringBootApplication
public class MyApplication{
    @Bean
    public WebClient rest(ReactiveClientRegistrationRepository clients,
                          ServerOAuth2AuthorizedClientRepository authz) {

您在这里看到,只有 1 个类实现了接口 ReactiveClientRegistrationRepository,所以我的正确猜测是,如果只有一个类实现它,那么 autowired 将自动成为 clients 参数

public final class InMemoryReactiveClientRegistrationRepository
        implements ReactiveClientRegistrationRepository, Iterable<ClientRegistration> {

另一方面,ServerOAuth2AuthorizedClientRepository 由 3 个不同的类实现,即

public final class AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository
        implements ServerOAuth2AuthorizedClientRepository {


public class UnAuthenticatedServerOAuth2AuthorizedClientRepository implements ServerOAuth2AuthorizedClientRepository {



public final class WebSessionServerOAuth2AuthorizedClientRepository
        implements ServerOAuth2AuthorizedClientRepository {

调试后,得到的类是AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository

spring boot 框架如何知道哪个是哪个?我认为会有bean冲突,比如这个问题Spring boot autowiring an interface with multiple implementations

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    ServerOAuth2AuthroizedClientRepostiryAuthenticatedPrincipalServerOAuth2AuthorizedClientRepository 的实例的原因是因为 Spring 默认会查找解析为类型 ServerOAuth2AuthroizedClientRepiository 的 bean,但如果不存在,则会创建一个新的 AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository 对象。

    如果你想覆盖它,你可以使用你选择的类型创建一个新的 Bean。

    @Bean
    ServerOAuth2AuthroizedClientRepostiry repository() {
        return new WebSessionServerOAuth2AuthorizedClientRepository(...);
    }
    

    【讨论】:

    • 但是没有用于选择哪一个的限定符。这是我从文档中获得的标准代码。
    • 抱歉,我以为那些是自定义实现,我会编辑我的帖子。
    • 如果它们不是 bean,Spring 将什么/如何将它们注入 rest @Bean 带注释的工厂方法?
    • 哦,哇,是的,看起来他们确实先寻找豆子,然后再求助于班级成员。
    • 文档有什么用? OP 有一个 MyApplication 配置类和一个 @Bean 工厂方法。他们声称该方法接收AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository 对象。如果它不是 bean,那么该对象来自哪里?
    猜你喜欢
    • 2019-01-16
    • 1970-01-01
    • 2015-10-09
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-21
    • 2017-05-11
    相关资源
    最近更新 更多