【问题标题】:failed to autowired annotation未能自动装配注释
【发布时间】:2012-02-23 22:47:56
【问题描述】:

为什么我在执行时总是得到 userDetailDao 异常 null :

package com.springweb.service;

import com.springweb.dao.UserDetailDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.dao.DataAccessException;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

public class UserService implements UserDetailsService
{    
    @Autowired
    UserDetailDao userDetailDao;

    public UserDetails loadUserByUsername(String string) throws UsernameNotFoundException, DataAccessException {
        return userDetailDao.queryForUser(string);
    }

}

在我的春季安全配置中:

<security:authentication-provider user-service-ref="userService">
    <security:password-encoder hash="md5" />        
</security:authentication-provider>

<bean name="userService" class="com.springweb.service.UserService">
</bean>

在我的调度程序上下文中,我已经定义扫描包:

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

【问题讨论】:

    标签: spring annotations autowired


    【解决方案1】:

    我猜你的 UserDetailDao 是在 DispatcherServlet 上下文中声明的,因此在声明 userService 的根 webapp 上下文中是不可访问的。因此,UserDetailsDao 应该在根上下文中声明为 bean。

    您还需要在根上下文中使用&lt;context:annotation-driven/&gt;

    一般来说,你现在有一个 bean 的重复 - bean 是由 &lt;context:component-scan&gt; 添加到 DispatcherServlet 上下文中的,并且相同类的 bean 是在根上下文中手动声明的。这种情况应该避免——你需要更仔细地指定&lt;context:component-scan&gt;要扫描的包。

    另请参阅:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 2018-03-13
      • 2015-03-17
      • 1970-01-01
      • 2011-03-10
      • 2014-06-30
      • 1970-01-01
      相关资源
      最近更新 更多