无法注入实现多个接口的bean

问题描述 投票:1回答:1

在我的Spring Boot应用程序中,我有以下bean

@Service
public class AppUserDetailsService implements UserDetailsService {
    // implementation omitted
}

我将此bean注入到下面的类中

@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private AppUserDetailsService appUserDetailsService;
    // remainder of implementation omitted
}

如果我更改bean以便实现多个接口,即

@Service
public class AppUserDetailsService implements UserDetailsService, UserService {
    // implementation omitted
}

依赖项注入失败,并出现以下错误

由以下原因引起:org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为'securityConfiguration'的bean时出错:通过字段'appUserDetailsS​​ervice'表示的不满足的依赖性;

为什么向bean添加第二个接口会导致依赖项注入失败?

如果我将@Autowired成员更改为使用接口类型而不是类类型,也会发生此问题,>

@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService appUserDetailsService;
    // remainder of implementation omitted
}

在我的Spring Boot应用程序中,我有以下bean @Service公共类AppUserDetailsS​​ervice实现UserDetailsS​​ervice {//省略了实现}我将此bean注入到@ ...下面的类中。

我相信在您的情况下,Spring引擎首先试图确定按类型提供bean的位置,并且在单个bean中实现了多个类型,这使它对解析器感到困惑。
并非与该问题完全相同:Spring behaviour when using interface name also as a bean name?
但是您可以尝试将Qualifier用于Bean,以明确表示您希望注入该Bean。
java spring spring-boot
1个回答
0
投票
但是您可以尝试将Qualifier用于Bean,以明确表示您希望注入该Bean。
© www.soinside.com 2019 - 2024. All rights reserved.