java - Spring MVC 在使用 Component 注释时未检测到 bean

标签 java spring spring-mvc

web.xml 文件:

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/root-context.xml, /WEB-INF/spring-security.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

servlet-context.xml 包含:

<context:component-scan base-package="com.kb.*" />

spring-security.xml 包含:

<!-- if uncoment the below line then customAuthenticationProvider is detected -->
<!--    <beans:bean id="customAuthenticationProvider" class="com.kb.authentication.provider.CustomAuthenticationProvider" />
 -->
    <authentication-manager erase-credentials="true">
        <authentication-provider ref="customAuthenticationProvider" />
    </authentication-manager>

和主要部分,

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider { ...

customAuthenticationProvider 是用 @Component 注解的,为什么 spring 检测不到它?我收到错误:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customAuthenticationProvider'

xml配置有错误,可能是什么原因?

最佳答案

简短回答: 使用正确的基础包名称。

更长的答案: 这不是基本包名称:com.kb.*。 这是一个包名的梦想。

相反,请使用正确的基础包名称。例如,com.kb

更多答案: 身份验证提供程序中的 ref="customAuthenticationProvider" 属性似乎是问题所在。 具体来说,没有引用 ID 为 customAuthenticationProvider 的 bean。

尝试在 CustomAuthenticationProvider 类上使用 @Qualifier 注释。

关于java - Spring MVC 在使用 Component 注释时未检测到 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40749332/

相关文章:

java - 在 Rest API 的查询参数中发送 pct (%)

java - 如何使用 Spring Controller 解析 Apache Tiles 定义

java - Spring Boot 应用程序未启动。错误 : Stopping Service [Tomcat]

java - 使用 Tomcat 进行基于表单的身份验证

java - 将两个 for 循环合并为一个

使用 WebSockets 的 Spring Security - 禁止 403

java - 为什么 RequestBody 不会绑定(bind)到我的 java 模型?

java - 如何使用 @ControllerAdvice 在 Spring MVC 中返回 ResponseEntity 的方法中返回错误消息

java - 如何以一种形式在两个保管箱中传递两个列表

java.lang.NullPointerException** 错误?