NoSuchBeanDefinitionException:找不到依赖项

时间:2015-06-18 17:10:52

标签: hibernate spring-mvc authentication

当我尝试在Eclipse中运行项目时,我收到以下错误。我尝试了类似问题的不同解决方案,但无法弄清楚确切的问题。

  

org.springframework.beans.factory.BeanCreationException:创建名为'org.springframework.security.filterChains'的bean时出错:设置bean属性时无法解析对bean'org.springframework.security.web.DefaultSecurityFilterChain#1'的引用带有键[1]的'sourceList';嵌套异常是org.springframework.beans.factory.BeanCreationException:创建名为'org.springframework.security.web.DefaultSecurityFilterChain#1'的bean时出错:无法解析对bean的引用'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#使用key [4]设置构造函数参数时为0';嵌套异常是org.springframework.beans.factory.BeanCreationException:创建名为'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0'的bean时出错:无法解析对bean的引用'org.springframework.security.authentication.ProviderManager#设置bean属性'authenticationManager'时为0';嵌套异常是org.springframework.beans.factory.BeanCreationException:创建名为'org.springframework.security.authentication.ProviderManager#0'的bean时出错:无法解析对bean的引用'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#设置构造函数参数时为0';嵌套异常是org.springframework.beans.factory.BeanCreationException:创建名为'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0'的bean时出错:FactoryBean在创建对象时抛出异常;嵌套异常是org.springframework.beans.factory.BeanCreationException:创建名为'org.springframework.security.authenticationManager'的bean时出错:在使用key [0]设置构造函数参数时无法解析对bean'authService'的引用;嵌套异常是org.springframework.beans.factory.BeanCreationException:创建名为'authService'的bean时出错:注入自动连接的依赖项失败;嵌套异常是org.springframework.beans.factory.BeanCreationException:无法自动装配字段:com.demo.dao.UserDAO com.demo.service.impl.AuthServiceImpl.userDao;嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:找不到类型为[com.demo.dao.UserDAO]的限定bean依赖:预期至少有1个bean符合此依赖关系的autowire候选者。依赖注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}       在org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:336)

我的security.xml是:

<context:property-placeholder location="classpath*:META-INF/spring/*.properties"/>

<http pattern="/resources/**" security="none"/>

<http access-decision-manager-ref="accessDecisionManager" use-expressions="true">
    <intercept-url pattern="/forgotPasswordJson" access="permitAll" />
    <intercept-url pattern="/resetPassword" access="permitAll" />
    <intercept-url pattern="/login" access="permitAll" />
    <intercept-url pattern="/logout" access="permitAll" />
    <intercept-url pattern="/loginfailed" access="permitAll" />
    <intercept-url pattern="/setTimezoneOffset" access="permitAll" />
    <intercept-url pattern="/images/**" access="permitAll" />
    <intercept-url pattern="/info/termsOfService" access="permitAll" />
    <intercept-url pattern="/**" access="hasRole('USER')" />
    <form-login login-page='/login' authentication-failure-url="/loginfailed" authentication-success-handler-ref="customAuthenticationHandler" />
    <logout delete-cookies="JSESSIONID" logout-success-url="/login" logout-url="/logout" invalidate-session="true"/>
    <session-management session-authentication-error-url="/loginfailed" session-fixation-protection="newSession">
        <concurrency-control max-sessions="100" error-if-maximum-exceeded="true" />
    </session-management>
</http>

<authentication-manager>
    <authentication-provider ref="authService" />
</authentication-manager>
<beans:bean id="authService" class="com.demo.service.impl.AuthServiceImpl" />
<beans:bean id="customAuthenticationHandler" class="com.demo.security.CustomAuthenticationSuccessHandler" />

我的DaoImpl是:

@SuppressWarnings("unchecked")
@Override
public User findUser(String userName, boolean allData)
{
    if (logger.isDebugEnabled()) logger.debug("Finding user by user name \"" + userName + "\"");

    List<User> list = entityManager.createQuery("from User u where upper(u.userName) = :name")
            .setParameter("name", userName.toUpperCase()).getResultList();

    if (list.size() != 1) return null;
    User u = list.get(0);

    if (u != null && allData)
    {
        Hibernate.initialize(u.getClients());
        Hibernate.initialize(u.getRoles());
    }

    return u;
}

我的AuthServiceImpl是:

@Service
public class AuthServiceImpl implements AuthSerice, AuthenticationProvider {

@Autowired
UserDAO userDao;
@Override
public Authentication authenticate(Authentication authentication) 
  throws AuthenticationException {
    System.out.println("Entered Java auth");
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();

    User details = userDao.findUser(name, true);
    Collection<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
    SimpleGrantedAuthority userAuthority = new SimpleGrantedAuthority(
            "ROLE_USER");
    SimpleGrantedAuthority adminAuthority = new SimpleGrantedAuthority(
            "ROLE_ADMIN");
    authorities.add(userAuthority);
    authorities.add(adminAuthority);

    if (password.equals(details.getPassword())) {
        return new UsernamePasswordAuthenticationToken(name, password, authorities);
    } else {
        //throw new AuthenticationException("Unable to auth against third party systems");
        return null;
    }
}

@Override
public boolean supports(Class<?> authentication) {
    return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}

我的web.xml是:

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://java.sun.com/xml/ns/javaee"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
     id="WebApp_ID" 
     version="2.5"
     metadata-complete="true">

<display-name>MainWebsite</display-name>

<session-config>
    <session-timeout>120</session-timeout>
</session-config>

<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/root-context.xml
                 /WEB-INF/spring/security.xml</param-value>
</context-param>

<!-- Filters -->
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

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

<!-- Processes application requests -->
<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/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<jsp-config>
    <taglib>
        <taglib-uri>/spring</taglib-uri>
        <taglib-location>/WEB-INF/tld/spring-form.tld</taglib-location>
    </taglib>
</jsp-config>
</web-app>

在这里,我尝试从Java类中验证用户,而不是使用XML中的查询进行身份验证。

我的context:component-scan位于servlet-context.xml。如果我在<beans:bean class="com.demo.dao.impl.UserDAOImpl"/>中添加security.xml,则错误正在发生变化。我认为错误可能是因为xml加载优先级。

PS:错误的解决方法是将servlet-context.xml移动到WEB-INF文件夹,相应地重命名,然后在web.xml中添加/声明它XML文件..

1 个答案:

答案 0 :(得分:0)

com.vigillo.mainwebsiteroot包配置了类路径扫描,但您的类似乎位于com.demo包中。

所以你的意图似乎是明确声明com.demo类。

定义了authService和customAuthenticationHandler bean,但上下文中没有userDao。这可能就是问题所在。

定义它,看看会发生什么。

<beans:bean id="userDao" class="com.demo...UseDaoImpl"/>