Java 带有userDetailsService的Spring安全测试在测试用例中给出了illegalStateException

Java 带有userDetailsService的Spring安全测试在测试用例中给出了illegalStateException,java,spring-security,Java,Spring Security,我以前做过一些spring控制器测试,效果很好。 我最近使用userDetailsService添加了身份验证,现在当我运行控制器测试时,它说: java.lang.IllegalStateException: Failed to load ApplicationContext ... Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'nl

我以前做过一些spring控制器测试,效果很好。 我最近使用userDetailsService添加了身份验证,现在当我运行控制器测试时,它说:

java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'nl.kars.lms.service.MyUserDetailsService' available: 
expected at least 1 bean which qualifies as autowire candidate.
我不明白为什么,因为一切都应该正确配置。只有在运行控制器测试时才会发生这种情况,运行应用程序工作得非常好。这是我的课

测试用例

用户详细信息服务

我的问题是,如何阻止错误的发生?我做错了什么?我在这一点上迷路了。 谢谢

因为您在@ServiceuserDetailsService中将MyUserDetailsService命名为userDetailsService,所以您有两个选项

第一个: 在SecurityConfiguration中使用@QualifieruserDetailsService。 第二个选项:Autowire UserDetailsService,而不是SecurityConfiguration中的MyUserDetailsService

我建议你试试第一种选择

@Autowired
@Qualifier("userDetailsService")
MyUserDetailsService userDetailsService;

添加@Qualifier无效,但将MyUserDetailsService更改为UserDetailsService有效。谢谢
@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    MyUserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors();
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/**")
                .fullyAuthenticated()
                .and().httpBasic();
    }

    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
}
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private EmployeeService employeeService;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        return new EmployeeDetails(employeeService.getEmployeeByEmail(email));
    }
}
@Autowired
@Qualifier("userDetailsService")
MyUserDetailsService userDetailsService;