【问题标题】:spring application-security configuration bean scanspring应用程序安全配置bean扫描
【发布时间】:2014-07-07 14:52:02
【问题描述】:

在我的项目中,我需要一个自定义的 userDetailsS​​ervice,所以我在某个包中这样声明它:

@Service
@Ihm(name = "userDetailsService")// ignore Ihm, it's just a custom annotation, which works fine
public class UserDetailsServiceImpl implements UserDetailsService 

在我的 application-security.xml 文件中,我添加了组件扫描,

<context:component-scan base-package="path(including the userDetailsService for sure)" />

<context:annotation-config />

这并没有帮助我找到我的注释 bean,我得到了 bean 没有定义的异常。

在我的情况下唯一有效的方法是: 1.去掉服务注解 2.在 application-security.xml 中使用 beans:bean,id,class 创建 bean。 这很好用。

更有趣的是,当我同时保留组件扫描和注释时,我得到了一个 ID 重复(多个 bean,要求指定 ID)错误。

 More than one UserDetailsService registered. Please use a specific Id reference in <remember-me/> <openid-login/> or <x509 /> elements.

所以这意味着@Service 确实创建了 bean,但你不会在 security.xml 中找到它?

【问题讨论】:

  • 发布堆栈跟踪和其他配置。此外,在进行组件扫描时,bean 名称将是userDetailsServiceImpl&lt;context:annotation-config /&gt; 也隐含在 &lt;context:component-scan /&gt; 的使用中,因此您可能想要删除它。
  • 谢谢,你说得对,bean 的名字真的是 userDetailsS​​erviceImpl... 你能告诉我吗?如果名称是这样,Service 中的名称仅适用于注入东西的自动装配?

标签: spring spring-security spring-annotations spring-bean


【解决方案1】:

Spring Security 是在 bean 名称上自动连接 bean,对于 UserDetailsServiceuserDetailsService

@Service
public class UserDetailsServiceImpl implements UserDetailsService 

上面的代码(就像您的代码一样)将生成一个 UserDetailsService 类型的 bean,但是名称是 userDetailsServiceImpl 而不是 userDetailsService,因此 Spring Security 永远不会使用您的 bean,也不会被它检测到。 (命名约定见 Spring Reference Guide_

要解决此问题,请将 spring 安全配置和 put in a reference 更改为您的 userDetailsServiceImpl bean

<authentication-manager>
    <authentication-provider user-service-ref='userDetailsServiceImpl'/>
</authentication-manager>

或通过在 @Service 注释中提供名称来更改 bean 的名称。

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService 

任何一种方式都可以。

链接

  1. Using other authentication providers
  2. Naming autodetected components

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-02
    • 2015-01-13
    • 2011-04-24
    • 1970-01-01
    • 1970-01-01
    • 2012-09-02
    • 2016-11-09
    相关资源
    最近更新 更多