没有可用的'xxx.xxx.xxx.xxx.MyUserDetailsS​​ervice'类型的合格Bean:至少应有1个合格为自动装配候选的Bean

在尝试实现spring-security时,我始终收到上述错误。请帮忙,因为我还不熟悉Spring MVC

我尝试使用提供的解决方案

No qualifying bean of type available in SpringBoot Application

No qualifying bean of type 'concert.PerformanceImp' available

和其他一些,但我不知道为什么问题仍然存在

我的代码


/** spring security configurer **/

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    MyUserDetailsService userDetailsService;    


    @Autowired
    public void configureGlobal(AuthenticationmanagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }


    @Override
    protected void configure (HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                /**
                 * None of these urls requires authentication and any other urls
                 * not specified here,will require authentication
                 */
                .antMatchers(
                        "/","/about","/account/create"
                ).permitAll();

        http
            .formLogin()
                .loginPage("/account/login")
                .usernameParameter("email")
                .permitAll()
                .and()
                    .logout()
                    .permitAll();
    }
}



/** Custom UserDetailsService **/
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private accountDao accountDao;

    @Override
    public UserDetails loadUserByusername(String email) throws usernameNotFoundException {
        account account = accountDao.findaccountByEmail(email);
        System.out.println("User " + account );

        if(account == null ) {
            throw new usernameNotFoundException(
                    "User " + email + " was not found in database");
        }

        return (UserDetails) account;
    }
}




/** Front Controller **/

@Configuration
@EnableWebMvc

// the package set on component scan is the parent package,and every other packages are within it
// as some suggestions from slackoverflow pointed that it could be that the package of 
// MyUserDetailsService is not seen by the component scan 

@ComponentScan(basePackages= {"com.springmvcproject.concertio"})
public class FrontController implements WebMvcConfigurer {

    @Bean(name="messageSource")
    public MessageSource getMessageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("messages");
        return messageSource;
    }


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/concertio/resources/**").addResourceLocations("/")
        .setCachePeriod(31556926);
    }


    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }



    @Bean
    InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setRequestContextAttribute("requestContext");

        return resolver;
    }

}

服务器错误日志

Nov 06,2019 6:01:37 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener]
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfig': Unsatisfied dependency expressed through field 'userDetailsService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.springmvcproject.concertio.service.MyUserDetailsService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:581)
    at org.springframework.beans.factory.annotation.Injectionmetadata.inject(Injectionmetadata.java:91)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcesspropertyValues(AutowiredAnnotationBeanPostProcessor.java:367)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1340)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:756)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:409)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:291)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4666)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5136)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
    at java.base/java.util.concurrent.Futuretask.run(Futuretask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:831)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
    at java.base/java.util.concurrent.Futuretask.run(Futuretask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:423)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:928)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:638)
    at java.base/jdk.internal.reflect.NativeMethodaccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodaccessorImpl.invoke(NativeMethodaccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodaccessorImpl.invoke(DelegatingMethodaccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:350)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:492)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.springmvcproject.concertio.service.MyUserDetailsService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1501)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1099)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1060)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:578)
    ... 45 more

Nov 06,2019 6:01:37 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: One or more listeners failed to start. Full details will be found in the appropriate container log file
Nov 06,2019 6:01:37 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/concertio] startup failed due to previous errors
Nov 06,2019 6:01:37 PM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
Nov 06,2019 6:01:37 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Nov 06,2019 6:01:37 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Nov 06,2019 6:01:37 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in [7,536] milliseconds

我也使用了与OP相同的步骤

Spring security Cant autowire UserDetailsService

但错误仍然存​​在...任何帮助将不胜感激

yushangzfds2008 回答:没有可用的'xxx.xxx.xxx.xxx.MyUserDetailsS​​ervice'类型的合格Bean:至少应有1个合格为自动装配候选的Bean

通过@PraveenKumarLalasangi的帮助,我能够解决上述错误...

这是当前的工作代码库

SecurityConfig


@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;


    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    .....
    .....
    .....

}

MyUserDetailsS​​ervice

@Component
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private AccountDao accountDao;

    @Transactional(readOnly=true)
    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        Account account = accountDao.findAccountByEmail(email);
        System.out.println("User " + account );

        if(account == null ) {
            throw new UsernameNotFoundException(
                    "User " + email + " was not found in database");
        }

        return (UserDetails) account;
    }
}

FrontController


@Configuration
@EnableWebMvc
@ComponentScan(basePackages= {"com.springmvcproject.concertio"})
public class FrontController implements WebMvcConfigurer {
     @Bean(name="messageSource")
    public MessageSource getMessageSource() { .....  }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {....}

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { .... }

   @Bean
    InternalResourceViewResolver viewResolver(){ .... }
}

WebConfig

public class WebConfig extends AbstractAnnotationConfigDispatcherServletInitializer{

    @Override
    protected Class<?>[] getRootConfigClasses() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] {
            FrontController.class
        };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] {
            "/" 
        };
    }

}

我希望有人会觉得有用

,

Spring使用其配置来查找和构造其上下文。作为其配置的一部分,您可以指定Bean类位于何处(在哪个包中)。 @ComponentScan(basePackages= {"com.springmvcproject.concertio"})告诉Spring Bean与com.springmvcproject.concertio包或其子包相关联。 MyUserDetailsService类是否放在此程序包或子程序包中?

本文链接:https://www.f2er.com/3150152.html

大家都在问