首页 > 解决方案 > 在 Spring Boot 中创建自定义安全配置时出现错误

问题描述

ConfigServletWebServerApplicationContext:上下文初始化期间遇到异常 - 取消刷新尝试:org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“securityConfig”的bean时出错:通过字段“readerRepository”表示不满足的依赖关系;嵌套异常是 org.springframework.beans.factory.BeanCreationException:创建名为“readerRepository”的 bean 时出错:调用 init 方法失败;嵌套异常是 java.lang.IllegalArgumentException: Not a managed type: class java.io.Reader

package com.example.readinglist;

import java.io.Reader;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Repository;

@Repository
public interface ReaderRepository extends JpaRepository<Reader, String> {

    UserDetails findOne(String username);

}

阅读清单应用:

package com.example.readinglist;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ReadinglistApplication {

    public static void main(String[] args) {
        SpringApplication.run(ReadinglistApplication.class, args);
    }

}

安全配置文件:

package com.example.readinglist;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private ReaderRepository readerRepository;


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

        http.authorizeRequests()
        .antMatchers("/")
        .access("hasRole('Reader')")
        .antMatchers("/**").permitAll().and().formLogin().loginPage("/login")
        .failureUrl("/login?error=true");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(new UserDetailsService(){

            @Override
            public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
                return readerRepository.findOne(username);
            }
        });
    }
}

标签: spring-bootspring-security

解决方案


您导入了错误的 Reader 实体 --> 您导入了“import java.io.Reader;” 您需要导入您的自定义 Reader 实体类。


推荐阅读