Spring security 无法自动装配 UserDetailsS​​ervice

2023-12-07

我在尝试从数据库添加身份验证时遇到了困难。

这是错误日志:

2015 年 12 月 23 日 08:24:32.819 严重 [localhost-startStop-1] org.springframework.web.context.ContextLoader.initWebApplicationContext 上下文初始化失败 org.springframework.beans.factory.BeanCreationException:错误 创建名称为“securityConfig”的 bean:注入自动装配 依赖失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:无法 自动装配字段: org.springframework.security.core.userdetails.UserDetailsS​​ervice kamienica.configuration.SecurityConfig.userDetailsS​​ervice;嵌套的 例外是 org.springframework.beans.factory.NoSuchBeanDefinitionException:否 合格的 bean 类型 [org.springframework.security.core.userdetails.UserDetailsS​​ervice] 找到依赖项:预计至少有 1 个符合条件的 bean 此依赖项的自动装配候选者。依赖注释: {@org.springframework.beans.factory.annotation.Autowired(必需= true), @org.springframework.beans.factory.annotation.Qualifier(value=customUserDetailsS​​ervice)} 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) 在 org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302) 在 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) 在 org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298) 在 org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703) 在 org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760) 在 org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482) 在 org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403) 在 org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306) 在 org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106) 在 org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727) 在 org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167) 在 org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) 在 org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725) 在 org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701) 在 org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717) 在 org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586) 在 org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1750) 在 java.util.concurrent.Executors$RunnableAdapter.call(未知 源)位于 java.util.concurrent.FutureTask.run(未知源)位于 java.util.concurrent.ThreadPoolExecutor.runWorker(来源未知)位于 java.util.concurrent.ThreadPoolExecutor$Worker.run(来源未知) java.lang.Thread.run(来源不明) 原因: org.springframework.beans.factory.BeanCreationException:无法 自动装配字段: org.springframework.security.core.userdetails.UserDetailsS​​ervice kamienica.configuration.SecurityConfig.userDetailsS​​ervice;嵌套的 例外是 org.springframework.beans.factory.NoSuchBeanDefinitionException:否 合格的 bean 类型 [org.springframework.security.core.userdetails.UserDetailsS​​ervice] 找到依赖项:预计至少有 1 个符合条件的 bean 此依赖项的自动装配候选者。依赖注释: {@org.springframework.beans.factory.annotation.Autowired(必需= true), @org.springframework.beans.factory.annotation.Qualifier(value=customUserDetailsS​​ervice)} 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508) 在 org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289) ... 26 更多 原因: org.springframework.beans.factory.NoSuchBeanDefinitionException:否 合格的 bean 类型 [org.springframework.security.core.userdetails.UserDetailsS​​ervice] 找到依赖项:预计至少有 1 个符合条件的 bean 此依赖项的自动装配候选者。依赖注释: {@org.springframework.beans.factory.annotation.Autowired(必需= true), @org.springframework.beans.factory.annotation.Qualifier(value=customUserDetailsS​​ervice)} 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1103) 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:963) 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858) 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480) ... 28 更多

和我的配置类:

1)应用程序配置。

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "kamienica")
public class AppConfig {

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setContentType("UTF-8");
        return viewResolver;
    }

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

}

2)应用初始化程序:

public class AppInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext container) throws ServletException {

        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(AppConfig.class);
        ctx.setServletContext(container);

        ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));

        // added to handle local characters
        FilterRegistration.Dynamic fr = container.addFilter("encodingFilter", new CharacterEncodingFilter());
        fr.setInitParameter("encoding", "UTF-8");
        fr.setInitParameter("forceEncoding", "true");
        fr.addMappingForUrlPatterns(null, true, "/*");

        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");

    }

}

现在是最重要的部分:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")
    UserDetailsService userDetailsService;

    //
    // @Autowired
    // CustomSuccessHandler customSuccessHandler;
    //
    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
        auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/", "/index").permitAll().antMatchers("/Admin/**")
                .access("hasRole('ADMIN')").antMatchers("/User/**").access("hasRole('ADMIN') or hasRole('USER')")
                // .and().formLogin().loginPage("/login")
                .and().formLogin()
                // .loginPage("/login")
                // .successHandler(customSuccessHandler)
                // .usernameParameter("email").passwordParameter("password")
                // .and().csrf()
                // .and().exceptionHandling().accessDeniedPage("/Access_Denied")
        ;
    }
}

我的定制用户服务:

@Component
@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    TenantService tenantService;

    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {

        Tenant tenant = tenantService.loadByMail(email);

        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority(tenant.getRole()));
        return new org.springframework.security.core.userdetails.User(tenant.getEmail(), tenant.getPassword(), true,
                true, true, true, authorities);
    }

}

我在这里做错了什么?

编辑1。 我修改了以下文件中的注释,但没有解决问题:

@Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    TenantService tenantService;

    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {

        Tenant tenant = tenantService.loadByMail(email);

        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority(tenant.getRole()));
        return new org.springframework.security.core.userdetails.User(tenant.getEmail(), tenant.getPassword(), true,
                true, true, true, authorities);
    }

}

And:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService;

    //
    // @Autowired
    // CustomSuccessHandler customSuccessHandler;
    //
    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
        auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/", "/index").permitAll().antMatchers("/Admin/**")
                .access("hasRole('ADMIN')").antMatchers("/User/**").access("hasRole('ADMIN') or hasRole('USER')")
                // .and().formLogin().loginPage("/login")
                .and().formLogin()
                // .loginPage("/login")
                // .successHandler(customSuccessHandler)
                // .usernameParameter("email").passwordParameter("password")
                // .and().csrf()
                // .and().exceptionHandling().accessDeniedPage("/Access_Denied")
        ;
    }
}

编辑2:根据塞尔瓦的建议:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    CustomUserDetailsService customUserDetailsService;

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService);
        auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/", "/index").permitAll().antMatchers("/Admin/**")
                .access("hasRole('ADMIN')").antMatchers("/User/**").access("hasRole('ADMIN') or hasRole('USER')")
                .and().formLogin();
    }
}

不幸的是同样的结果:

没有合格的 bean 类型 找到 [kamienica.service.CustomUserDetailsS​​ervice] 依赖项: 预计至少有 1 个有资格作为自动装配候选者的 bean 这种依赖。依赖注释: {@org.springframework.beans.factory.annotation.Autowired(必需= true)}


  1. 要么使用@Component or @Service with CustomUserDetailsService, 不是都。
  2. 如果您正在使用@Service,然后像这样使用它:

    @Service("userDetailsService")

  3. 现在摆脱@Qualifier。只需使用:

    @Autowired UserDetailsService userDetailsService;

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring security 无法自动装配 UserDetailsS​​ervice 的相关文章

随机推荐

  • 如何保持元素:即使点击后仍处于活动状态

    从中得到了非常模糊和不需要的答案question所以我决定发布一个明确的问题来介绍我面临的问题 我正在使用的代码如下所示 flipClass font size Large background color 4399CD color fff
  • 在函数内执行 mysqli_query

    我有一个函数列表函数 php 我正在升级Mysql to Mysqli因为我刚刚学习Mysql现已弃用 我在顶级connect php 文件中声明我的连接 第一个文件是必需的 我所有的功能都使用mysql query QUERY 总是运行良
  • Telegram Api - 创建授权密钥 404 错误

    我正在尝试用 python 编写一个简单的程序来使用 telegram api 不是机器人 api 主要消息传递 api 现在我已经编写了这段代码 usr bin env python import socket import random
  • ASP.NET 自定义用户控件动态添加

    我很难将具有自定义用户控件的页面直接修改为 ASPX 页面 现在需要仅在需要时动态加载它 用户控件确实通过 ASCX 文件具有 html 和其他控件 并且在代码隐藏中具有代码 我已阅读多页 发现我无法直接实例化用户控件 但应该使用Page
  • Ubuntu 上的 Boost::system 链接错误

    我正在尝试编译以下实现上下文树切换的 C 代码 下载页面上有更多信息 Zip 存档 0 2 MB 这需要一些boost库 我从 boost org 下载了最新版本 并按照网站上的说明构建了所有需要构建的库 我还修改了存档中包含的 makef
  • 配置 emacs 以显示固定宽度的内嵌图像

    跟进 Emacs 组织显示内联图像 我按照 abo abo 的建议设法显示内联图像 现在我想为它们设置一个固定的宽度大小 设置 setq org image actual width 50 不起作用 Emacs 选择了该变量 但它没有对图像
  • 设置 ggplot 标题以反映 dplyr 分组

    我在 dplyr 中生成了一个分组数据框 其中每个组反映了因子变量水平的独特组合 我想使用类似的代码绘制不同的组this邮政 然而 我不知道如何在我的图的标题中包含两个 或更多 变量 这很麻烦 因为我有一堆不同的组合 假数据和绘图代码 li
  • scanf("%*[\n] %[^\n]", input_string); 是什么意思?做?

    我无法理解其中的区别 我用 n s 用于获取用户输入的短语 但当我需要添加两个短语时 这不起作用 但上面那个却做到了 请帮助我理解其中的区别 The n 指令告诉scanf 匹配换行符 以及 flag 表示不应进行任何分配 因此 n 跳过任
  • 使用intelliJ调试android中的后台服务

    我最近从 eclipse 切换到 IntelliJ 进行 Android 开发 由于更好的团队支持 项目 模块 但是 当我尝试调试后台服务时 似乎这是不可能做到的 有人成功让 IntelliJ 调试 bg 服务吗 非常感谢 本 有两种方法可
  • JavaScript 中动态加载的问题

    我是一名 JavaScript 新手 通过工作来学习pure计算数学函数的 JavaScript 项目 一切都运转良好 现在 作为进一步的一步 我想让消息传递多语言 该代码应该能够在运行时加载适当的语言文件 对于动态加载问题 我在网页上阅读
  • Matplotlib 自定义标记/符号

    So there is this guide http matplotlib org examples pylab examples scatter symbol html http matplotlib org examples pyla
  • 无法从 Alpha Vantage API 获取实时价格。价格为一天前的价格

    我正在尝试从 Alpha Vantage API 获取最新的盘中价格 目前是东欧时间星期五晚上 9 16 我正在尝试购买特斯拉股票 市场仍然开放 但是 API 调用仅返回昨天的数据 可能是什么问题呢 ts TimeSeries key AP
  • Powershell:将参数和管道输入转发到别名函数

    如何将所有管道输入和参数转发到别名函数内的命令 例如 如果我想给 tail 添加别名 function tail coreutils tail args 可以很好地配合tail n 5 test txt 但不与cat test txt ta
  • Bitbucket - 如何禁用奇怪的无意义的有色人[重复]

    这个问题在这里已经有答案了 我使用位桶 最近 每次按下按钮后 我开始在控制台中看到一个大个子黑人 自上周以来 它出现的频率越来越高 这使得我在控制台的登录时间更长 而且根本不方便工作 有什么方法可以完全禁用它吗 我不想看到它 我只想要吉特
  • 将二进制文件读入bash中的变量中

    我有以下 bash 脚本 我希望文件 out 1 和 out 2 相同 但它们是不同的 我怀疑问题在于 bash 如何处理二进制文件 那么在 bash 中将二进制文件读入变量的正确方法是什么 curl s http cacerts digi
  • 如何在android中实现调用键盘事件监听

    我想实施我的BroadcastReceiver按某些组合键时 假设我用键盘拨打 1234 他们是我的BroadcastReceiver将被调用 我可以通过什么启动我的活动 这是我解决这个问题的方法 这是我解决这个问题的方法 public c
  • Xcode 在处理程序中的 Stray '\342' 时给出了三个语法错误[重复]

    这个问题在这里已经有答案了 我正在 Xcode 中的 Objective C 中开发一个简单的项目 并且我收到了有关以下代码行的一些杂散 错误 if celsius lt 273 15 NSLog It is impossible to c
  • C++ 将一堆值与给定值进行比较

    我需要将一个给定值与检索到的值进行比较 我在代码中多次这样做 我对它的外观不满意 我正在寻找某种 util 函数 有人写过一篇吗 我要比较的值的数量在编译时是已知的 Update 我想摆脱容器 因为我知道我想要比较的确切值数量 通常不超过
  • 使用 Play 框架将生成的图像发送到浏览器

    我正在尝试使用 Play 输出生成的图像 我不确定我的问题是否与 Play 相关 我正在尝试执行与此 PHP 代码相同的操作 header Content type Image png map imagecreatefrompng SESS
  • Spring security 无法自动装配 UserDetailsS​​ervice

    我在尝试从数据库添加身份验证时遇到了困难 这是错误日志 2015 年 12 月 23 日 08 24 32 819 严重 localhost startStop 1 org springframework web context Conte