【问题标题】:Could not autowire. There is more than one bean of 'UserDetailsService' type [duplicate]无法自动接线。有多个“UserDetailsS​​ervice”类型的bean [重复]
【发布时间】:2020-10-03 09:12:25
【问题描述】:

我正在使用 IntelliJ Idea IDE 运行代码,但它显示无法自动装配。 'UserDetailsS​​ervice' 类型的 bean 不止一个。但是 Eclipse IDE 中的相同代码运行正常。 这是关于 Spring Security 的代码。请帮助我修复代码中的错误。

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public AuthenticationProvider authProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService());
        provider.setPasswordEncoder(new BCryptPasswordEncoder());
        return provider;
    }
}

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository repo;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = repo.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("404");
        }
        return new UserPrincipals(user);
    }
}

public class UserPrincipals implements UserDetails {

    private User user;

    public UserPrincipals(User user) {
        this.user = user;
    }

    @Override
    public Collection << ? extends GrantedAuthority > getAuthorities() {
        return Collections.singleton(new SimpleGrantedAuthority("USERS"));
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}

public interface UserRepository extends JpaRepository < User, Long > {
    User findByUsername(String username);
}

为什么 IntelliJ Idea 显示这种类型的错误是我的代码中的这个错误或其他错误,帮助我

【问题讨论】:

  • “但它显示无法自动装配”:您的意思是当您尝试运行它时?或者作为IDE中的警告?你试过在命令行中运行它吗?
  • IDE 中的警告

标签: spring spring-boot spring-mvc spring-security spring-data-jpa


【解决方案1】:
@Autowired
private UserDetailsService userDetailsService;

UserDetailsService 具有多个实现和 bean(包括您定义的 MyUserDetailsService),因此 Spring 不知道在上述情况下注入哪一个。

您需要使用@Qualifier 明确指定要注入的bean。像这样:

@Qualifier("MyUserDetailsService") 
private UserDetailsService userDetailsService

【讨论】:

    猜你喜欢
    • 2015-03-19
    • 2019-11-04
    • 2020-02-28
    • 2015-03-17
    • 2016-03-29
    • 1970-01-01
    • 2015-09-14
    • 2014-08-22
    • 2012-12-07
    相关资源
    最近更新 更多