spring security自动连接依赖项的注入失败

时间:2016-05-19 22:03:33

标签: hibernate spring-mvc spring-security

我已经查看了至少10个不同的答案,但没有一个建议有所帮助。

我刚开始使用Spring安全性而且我一直收到错误:

deque

这是我带到这一点的代码:

ApplicationContextConfig

spring security Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException

SpringWebAppInitializer

@EnableWebMvc
@Configuration
@ComponentScan(basePackages ="com.lisawestberg.noxml.controller, com.lisawestberg.noxml.service, com.lisawestberg.noxml.dao.impl, com.lisawestberg.noxml.domain")
@EnableTransactionManagement
@Import({ LoginConfig.class })
public class ApplicationContextConfig extends WebMvcConfigurerAdapter {



@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry
            .addResourceHandler("/resources/**")
            .addResourceLocations("/resources/");
}

@Bean(name = "viewResolver")
public InternalResourceViewResolver getViewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setPrefix("/WEB-INF/pages/");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
}

@Bean(name = "dataSource")
public DataSource getDataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("org.apache.derby.jdbc.ClientDriver");
    dataSource.setUrl("jdbc:derby://localhost:1527/School");
    dataSource.setUsername("root");
    dataSource.setPassword("rootroot");
    return dataSource;
}

private Properties getHibernateProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.show_sql", "false");
    properties.put("hibernate.hbm2ddl.auto", "update");
    properties.put("current_session_context_class", "thread");
    return properties;
}

@Autowired
@Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource) {
    LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
    sessionBuilder.addProperties(getHibernateProperties());
    sessionBuilder.addAnnotatedClass(Course.class);
    sessionBuilder.addAnnotatedClass(CourseStudent.class);
    sessionBuilder.addAnnotatedClass(Roll.class);
    sessionBuilder.addAnnotatedClass(Student.class);
    sessionBuilder.addAnnotatedClass(Faculty.class);
    return sessionBuilder.buildSessionFactory();
}

@Autowired
@Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
    HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
    return transactionManager;
}

@Autowired
@Bean(name = "courseDao")
public CourseDAO getCourseDao(SessionFactory sessionFactory) {
    return new CourseDaoImpl();
}

@Autowired
@Bean(name = "facultyDao")
public FacultyDAO getFacultyDao(SessionFactory sessionFactory) {
    return new FacultyDaoImpl();
}

@Autowired
@Bean(name = "rolesDao")
public RolesDAO getRolesDao(SessionFactory sessionFactory) {
    return new RolesDaoImpl();
}

@Autowired
@Bean(name = "studentDao")
public StudentDAO getStudentDao(SessionFactory sessionFactory) {
    return new StudentDaoImpl();
}

@Autowired
@Bean(name="courseStudentDao")
public CourseStudentDAO getCourseStudentDao(SessionFactory sessionFactory){
    return new CourseStudentDaoImpl();
}    
}

LoginConfig

public class SpringWebAppInitializer implements WebApplicationInitializer {

@Override
public void onStartup(ServletContext container) throws ServletException {
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.register(ApplicationContextConfig.class);
    context.setServletContext(container);
    context.register(LoginService.class, FacultyDAO.class);

    ServletRegistration.Dynamic dispatcher = container.addServlet("SpringDispatcher", new DispatcherServlet(context));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
}   
}

FacultyDaoImpl

@Configuration
@EnableWebSecurity
public class LoginConfig extends WebSecurityConfigurerAdapter {

@Autowired
@Qualifier("userDetailsService")
UserDetailsService userDetailsService;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests().antMatchers("/admin/**")
            .access("hasRole('ROLE_ADMIN')").and().formLogin()
            .loginPage("/login").failureUrl("/login?error")
            .usernameParameter("username")
            .passwordParameter("password")
            .and().logout().logoutSuccessUrl("/login?logout")
            .and().csrf()
            .and().exceptionHandling().accessDeniedPage("/403");
}

@Bean
public PasswordEncoder passwordEncoder() {
    PasswordEncoder encoder = new BCryptPasswordEncoder();
    return encoder;
}   
}

的UserDetailsS​​ervice

@Repository("facultyDao")
public class FacultyDaoImpl extends HibernateDao<Faculty,Integer> implements FacultyDAO {

@Override
public Faculty findByLogin(String login) {
    List<Faculty> allFaculty = new ArrayList<>();

    allFaculty = currentSession().createQuery("select f from faculty f where login = :login").list();

    if (!allFaculty.isEmpty()){
        return allFaculty.get(0);
    } else {
        return null;
    }
}
}

当然还有堆栈跟踪。我会把所有无聊的东西都给你。堆栈跟踪超过1000行:

@Service("userDetailsService")
public class LoginService implements UserDetailsService {

@Autowired
FacultyDAO dao;

@Transactional(readOnly = true)
public UserDetails loadUserByUsername(final String login) throws UsernameNotFoundException {
    Faculty faculty = dao.findByLogin(login);
    List<GrantedAuthority> authorities = buildUserAuthority(faculty.getRoles());
    return buildUserForAuthentication(faculty, authorities);
}

private User buildUserForAuthentication(Faculty faculty, List<GrantedAuthority> authorities) {
    return new User(faculty.getLogin(), faculty.getPassword(), faculty.isEnabled(), true, true, true, authorities);
}

private List<GrantedAuthority> buildUserAuthority(Set<Roll> roleSet) {
    Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
    // Build user's authorities
    for (Roll roles : roleSet) {
        setAuths.add(new SimpleGrantedAuthority(roles.getRoleTitle()));
    }
    List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);
    return Result;
}
}

1 个答案:

答案 0 :(得分:0)

不要忘记阅读最后的例外情况:

  

嵌套异常是   org.springframework.beans.factory.NoSuchBeanDefinitionException:没有   找到[com.lisawestberg.noxml.dao.FacultyDAO]类型的限定bean   对于依赖:预计至少有1个bean有资格作为autowire   这种依赖的候选人。依赖注释:   {@ org.springframework.beans.factory.annotation.Autowired(所需=真)}

您的bean声明不正确。你在getter上使用@Autowire了吗?

@Autowired
@Bean(name = "facultyDao")
public FacultyDAO getFacultyDao(SessionFactory sessionFactory) {
    return new FacultyDaoImpl();
}

@Autowire只能用于属性或setter,而不能用于getter。尽管春天正试图寻找一种可以注射的豆子,但此时它并没有。“

首先,从所有bean声明中删除@Autowire,并仅在想要自动注入(&#34; wire&#34;)bean实例的地方使用它。