Spring Security 配置自动装配自定义 UserDetailsS​​ervice bean

2024-01-02

我最近回到了我一直在从事的一个 Spring 项目,在启动应用程序时遇到了问题。这个问题可能是重复的,但我一直找不到答案。

这是我原来的 SecurityConfig.java 的一个片段:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired private UserService userService;

    /**
     * Global security config to set the user details service etc.
     * @param auth authentication manager
     * @throws Exception
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userService)
                .passwordEncoder(passwordEncoder());
    }

UserService 对象实现 UserDetailsS​​ervice。这在启动时出现错误:

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.clubmate.web.service.UserService com.clubmate.web.config.SecurityConfig.userService; nested exception is java.lang.IllegalArgumentException: Can not set com.clubmate.web.service.UserService field com.clubmate.web.config.SecurityConfig.userService to com.sun.proxy.$Proxy62
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    ... 58 more
Caused by: java.lang.IllegalArgumentException: Can not set com.clubmate.web.service.UserService field com.clubmate.web.config.SecurityConfig.userService to com.sun.proxy.$Proxy62
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
    at java.lang.reflect.Field.set(Field.java:764)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:569)
    ... 60 more

根据我的阅读,这是因为我自动装配了一个具体类而不是 UserDetailsS​​ervice 接口,但这对我来说很奇怪,因为当我之前处理这个项目时,自动装配具体类工作得很好。

我屈服了,只是将其更改为自动装配 SecurityConfig.java 中的 UserDetailsS​​ervice 接口。

我不确定这是否相关,但现在在启动时,对于我的任何其他 bean 对象,我收到以下错误(@Service等)有@Autowire private UserService userService.

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.clubmate.web.service.UserService com.clubmate.web.service.PageService.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.clubmate.web.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    ... 58 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.clubmate.web.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
    ... 60 more

非常感谢任何帮助。这已经让我发疯好几个小时了。

Update

更多信息:我有另一个配置类(AppConfig.java),其中包含以下内容:

@Configuration
@EnableWebMvc
@ComponentScan("com.clubmate.web")
@PropertySource(value = { "classpath:application.properties" })
@Import({
        SecurityConfig.class,
        CacheConfig.class,
        DatabaseConfig.class,
        CronConfig.class
})
public class AppConfig extends WebMvcConfigurerAdapter {
    // ...
}

我还有两个应用程序初始值设定项类,其中一个用于 MVC,它是:

public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    public Class<?>[] getRootConfigClasses() {
        return new Class[] {
                AppConfig.class
        };
    }

    @Override
    public Class<?>[] getServletConfigClasses() {
        return new Class[] {
                StartupHousekeeping.class,
                ShutdownHousekeeping.class
        };
    }

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

}

...另一个安全性是:

public class AppInitializer extends AbstractSecurityWebApplicationInitializer {

    private static Logger log = LogManager.getLogger(AppInitializer.class);

    @Override
    protected void beforeSpringSecurityFilterChain(ServletContext context) {
        // load multipart filter before other filters are created
        // see: http://docs.spring.io/spring-security/site/docs/4.0.1.RELEASE/reference/htmlsingle/#csrf-multipart
        MultipartFilter multipartFilter = new MultipartFilter();
        multipartFilter.setMultipartResolverBeanName("multipartResolver");
        insertFilters(context, multipartFilter);
    }

}

这些会以某种方式发生冲突吗?

Update 2

抛出异常的屏幕截图:https://i.stack.imgur.com/tcE5S.jpg https://i.stack.imgur.com/tcE5S.jpg

var1 是 SecurityConfig 类,var2 是一个 Proxy 对象,它应该是我的 UserService 类。


自动装配失败,因为默认情况下 Spring 使用 JDK 动态代理(通过实现其接口来代理目标类)创建代理。 另一方面,基于 CGLIB 的代理是目标类的子类。

See: JDK动态代理和CGLib有什么区别? https://stackoverflow.com/questions/10664182/what-is-the-difference-between-jdk-dynamic-proxy-and-cglib

要启用基于 CGLIB 的代理,请注释您的其中一项@Configuration课程与@EnableAspectJAutoProxy(proxyTargetClass=true):

@Configuration
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class AppConfig {
    ...
}

请注意,从版本 3.2 开始,CGLIB 已重新打包并包含在 spring-core JAR 中。因此,它开箱即用。

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

Spring Security 配置自动装配自定义 UserDetailsS​​ervice bean 的相关文章

随机推荐

  • 如何从 .m 文件创建可执行的 .exe 文件

    我想知道是否有一种方法可以在 MATLAB 中从 m 文件创建 exe 文件 这样它就可以在没有 MATLAB 的机器上运行 就像可以在 C C 中完成一样 我知道编写 MATLAB 函数是一种方法 但我不确定它是否可以在没有 MATLAB
  • JavaScript inflate 实现(可能仅限 FF 3.6)

    我正在编写一些在 FireFox 3 6 中使用 HTML 5 文件 API 的脚本 我有一些放气 压缩 的文件 我需要对它们进行充气 解压缩 我找到了一个few http www codeproject com KB scripting
  • 英特尔 XDK 中的 res/drawable 文件

    xdk中有没有办法将文件传输到android res drawable文件夹 我有以下文件 src android drawable noti icon png www src android drawable noti icon png
  • 长时间关闭时如何处理servlet请求

    我们需要在 Servlet 应用程序中实现优雅的关闭机制 编辑 我们希望使其尽可能简单 这将处理通过操作系统功能发送的终止信号 这将允许系统管理员使用内置的 shell 实用程序 Windows 上的kill 或taskkill 否则他们必
  • 反应本机保存屏幕到图像问题(react-native-view-shot 模块)

    我想得到反应本机视图镜头 https github com gre react native view shot工作 但我认为模块和我安装的 React Native 工具版本存在某种不兼容性 这阻碍了我的工作 核心问题似乎在于这段代码 i
  • 如何配置 OpenSL 来录制语音通话

    我正在使用 MediaRecorder 开发通话录音应用程序语音通话音频源 在某些棉花糖设备中它崩溃了 然后我将源更改为MIC这里传入的声音没有被记录 由于java的限制 现在我正在研究原生android代码来录制语音通话 我设法使用录制音
  • python 不被识别为内部或外部命令[重复]

    这个问题在这里已经有答案了 我尝试安装this https github com joyent node wiki Installation软件 为此需要Python 我从以下位置安装了Pythonhere http python org
  • PHP 中的随机 ID/数字生成器

    我正在我的数据库中构建一个 代理 ID 列表 满足以下要求 ID 长度必须为 9 位 仅限数字 ID 中的相同数字不得超过 3 个 ID 不能包含超过 2 个连续的相同数字 即 887766551 不能有 888 到目前为止 我已经完成了第
  • 在 Python 中将数据添加到嵌套列表

    我有一个嵌套列表 例如 nlist 1 2 3 4 5 6 7 8 9 在将此列表插入数据库之前 我想向其中添加一个 列 并在新列的每一行中具有相同的值 例如 nlist a 1 2 3 a 4 5 6 a 7 8 9 例如 当原始嵌套列表
  • MVC 4 Web API 帖子

    我想从远程客户端进行插入 因为我需要通过 http 发送数据 我可以使用getPerformances 正确地与httpClient api performances date 0 我想问一下我的postPorformances 我内部的实
  • ProcessBuilder 和 Runtime.exec() 之间的区别

    我正在尝试从 java 代码执行外部命令 但我注意到两者之间存在差异Runtime getRuntime exec and new ProcessBuilder start 使用时Runtime Process p Runtime getR
  • Linux/C++ 如何调试发布应用程序

    我有 linux c 多线程应用程序 现在它已经在生产服务器上进行了测试并且出现了段错误 问题是我无法在任何测试服务器上重现该错误 并且无法访问生产服务器 我没有转储或任何其他有用的信息 仅行 段错误位于 0000000046bf0fb8
  • JTree,始终以“编辑模式”显示所有节点

    我正在显示自定义对象树 并且我有自定义对象CellTreeEditor and CellTreeRenderer set 现在我真正想要的是始终像 编辑模式 一样显示所有对象 现在我有CellTreeRenderer getTreeCell
  • 姜戈/彗星(推):万恶之中最小的?

    我已阅读了我能找到的所有有关 Django 和 HTTP Push 的问题和答案 然而 没有人提供一个清晰 简洁 从头到尾的解决方案来说明如何实现所谓的 comet 功能的基本 hello world 第一个问题 1 HTTP 的问题在多大
  • 在 Shell 脚本中将 Cron 作业设置为每月的第一个工作日

    我是脚本语言新手 谁能解释一下如何设置第一个工作日的 cron 作业 您可以使用以下内容 monthly 每月第一天早上运行一次 0 0 1 home scripts your script file sh 第三次编辑 这将在该月第一个工作
  • 在 OpenCV 中创建 AVI 文件

    我一直在尝试使用 OpenCV 和 Visual Studio 2008 创建一个应用程序 从网络摄像头捕获图像 对它们应用过滤器 然后将它们写入 AVI 文件 除了创建 AVI 文件之外 一切正常 问题是它在我的计算机上可以运行 但在我同
  • HashSet 如何与 hashCode() 配合使用?

    我试图更深入地了解 java util Collection 和 java util Map 但我对 HashSet 功能有一些疑问 在文档中 它说 此类实现 Set 接口 由哈希表 实际上是 HashMap 实例 支持 好的 所以我可以看
  • 抓取 NSDictionary 中的随机条目

    有没有办法在 NSDictionary 中获取完全随机的密钥 NSString key enumeratorForKeysInDictionary nextObject 我有这段代码以非随机方式迭代字典 我应该将所有键添加到 NSSet 中
  • 如何授予apache写入主目录的权限?

    我的服务器位于 var www html 我在 var www html fileio test io test php 有一个 php 脚本 当我尝试运行这个脚本时 我得到 Warning fopen home djameson test
  • Spring Security 配置自动装配自定义 UserDetailsS​​ervice bean

    我最近回到了我一直在从事的一个 Spring 项目 在启动应用程序时遇到了问题 这个问题可能是重复的 但我一直找不到答案 这是我原来的 SecurityConfig java 的一个片段 Configuration EnableWebSec