You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring6升级Tomcat10时AuthenticationManager多Bean未标记primary问题

解决Spring 6 + Tomcat 10下AuthenticationManager多Bean注入异常

问题原因

升级后出现的依赖注入异常,是因为Spring Security在你的配置里生成了3个AuthenticationManager类型的Bean:

  • 你通过<security:authentication-manager>显式定义的authenticationManager
  • <security:http>模块默认自动创建的内部AuthenticationManager
  • <security:global-method-security>触发创建的AuthenticationManager实例

Spring容器无法确定注入时该选哪一个,所以需要指定主Bean(primary),或者调整配置减少冗余Bean。

解决方案一:标记自定义AuthenticationManager为Primary

直接在你显式配置的<security:authentication-manager>标签上添加primary="true"属性,告诉Spring这是优先选择的Bean:

<security:authentication-manager alias="authenticationManager" primary="true">
    <security:authentication-provider ref="authProvider"/>
</security:authentication-manager>

解决方案二:让HttpSecurity复用自定义AuthenticationManager

在<security:http>标签中通过authentication-manager-ref属性指定复用你定义的authenticationManager,这样Http模块就不会再自动创建新的AuthenticationManager,从根源减少Bean数量:

<security:http auto-config="false" create-session="stateless" entry-point-ref="http403ForbiddenEntryPoint" authentication-manager-ref="authenticationManager">
    <security:csrf token-repository-ref="csrfTokenRepository" disabled="true"/>

    <security:intercept-url pattern="/metrics/healthcheck" access="permitAll"/>
    <security:intercept-url pattern="/validation/healthcheck" access="permitAll"/>
    <security:intercept-url pattern="/actuator/info" access="permitAll"/>
    <security:intercept-url pattern="/actuator/health" access="permitAll"/>
    <security:intercept-url pattern="/error" access="permitAll"/>
    <security:intercept-url pattern="/" access="isAuthenticated()"/>

    <security:custom-filter position="PRE_AUTH_FILTER" ref="preauthFilter"/>
    <security:custom-filter before="CSRF_FILTER" ref="csrfHeaderPreFilter"/>
    <security:custom-filter after="CSRF_FILTER" ref="csrfHeaderFilter"/>
</security:http>

两种方案都能解决问题,方案二更推荐,因为它避免了冗余Bean的创建,让配置更清晰。

内容的提问来源于stack exchange,提问作者chaitalipatil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 22:34:53