有多个“UserDetailsS​​ervice”类型的 bean。

我无法在我的类 SecurityConfig 中自动装配 UserDetailsService,并且在尝试启动应用程序时出现错误。我不知道它不起作用,我已经开始了一个具有相同配置的项目。


SecurityConfig.java


package ma.wearesport.wearesport.security;


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.http.HttpMethod;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import org.springframework.security.config.annotation.web.builders.WebSecurity;

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import org.springframework.security.core.userdetails.UserDetailsService;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;


@Configuration

@EnableWebSecurity

public class SecurityConfig extends WebSecurityConfigurerAdapter {


  @Bean

  public BCryptPasswordEncoder bCryptPasswordEncoder() {

    return new BCryptPasswordEncoder();

  }


我尝试添加 @Qualifier("UserDetailsServiceImpl"),但它不起作用。


  @Autowired

  private UserDetailsService userDetailsService;

  @Autowired

  private BCryptPasswordEncoder passwordEncoder;


  @Override

  protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);

  }


  @Override

  public void configure(WebSecurity web) {

    super.configure(web);

  }


  @Override

  protected void configure(HttpSecurity http) throws Exception {

    http.csrf().disable();

    http.authorizeRequests().antMatchers(HttpMethod.POST, "api/register").permitAll();

  }

}


慕田峪7331174
浏览 142回答 2
2回答

慕的地10843

你有一个,因为你通过在定义它的 bean中BeanCurrentlyInCreationException自动装配 bean 来创建 bean 之间的循环依赖关系。BCryptPasswordEncoderSecurityConfig这是您必须删除的内容:@Autowiredprivate BCryptPasswordEncoder passwordEncoder;相反,您应该使用方法引用来引用BCryptPasswordEncoder:@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {  @Autowire  private UserDetailsService userDetailsService;  @Bean  public BCryptPasswordEncoder bCryptPasswordEncoder() {    return new BCryptPasswordEncoder();  }  @Override  protected void configure(AuthenticationManagerBuilder auth) throws Exception {    auth.userDetailsService(userDetailsService)        .passwordEncoder(bCryptPasswordEncoder());  }}或者在不扩展的BCryptPasswordEncoder单独类中声明bean 。@ConfigurationWebSecurityConfigurerAdapter

临摹微笑

您可以直接注入 UserDetailsServiceImpl :@Autowired private UserDetailsServiceImpl userDetailsService;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java