在Spring Boot中创建自定义安全配置时出现错误

时间:2020-03-13 07:11:44

标签: spring-boot spring-security

ConfigServletWebServerApplicationContext:遇到异常 在上下文初始化期间-取消刷新尝试: org.springframework.beans.factory.UnsatisfiedDependencyException: 创建名称为“ securityConfig”的bean时出错:不满意的依赖关系 通过字段“ readerRepository”表示;嵌套异常为 org.springframework.beans.factory.BeanCreationException:错误 创建名称为“ readerRepository”的bean:初始化方法的调用 失败嵌套异常是java.lang.IllegalArgumentException:不是 托管类型:类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);

}

ReadingListApplication:

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);
    }

}

SecurityConfiguration文件:

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);
            }
        });
    }
}

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

我认为readerRepository.findOne(username)不返回UserDetails对象。如果是这样,则必须基于Reader对象中的信息创建一个新的UserDetails对象,并将其返回

答案 2 :(得分:0)

您的存储库声明错误。 它必须是:

public interface ReaderRepository extends JpaRepository<<Name of your entity>, String> {

如果您的实体名称为Reader,则您输入了错误的类