无法自动连接Spring Security实现类

时间:2017-01-31 22:18:41

标签: java spring spring-security

我正在尝试为我的REST API创建BasicAuth,这是我的问题。

AccountConfiguration

// Spring Security uses accounts from our database
@Configuration
public class AccountConfiguration extends GlobalAuthenticationConfigurerAdapter {

    private UserAuthService userAuthService;

    @Autowired
    public AccountConfiguration(UserAuthService userAuthService) {
        this.userAuthService = userAuthService;
    }

    @Override
    public void init(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userAuthService);
    }
}

在构造函数中,IntelliJ告诉我

  

无法自动装配。没有找到“UserAuthService类型”的bean

但是我把那个bean放在同一个包里,这里是:

@Service
@Transactional
public class UserAuthService implements UserDetailsService {

    private UserRepository userRepository;

    @Autowired
    public UserAuthService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);

        if (user == null) {
            throw new UsernameNotFoundException("Could not find the user: " + username);
        }

        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                true,
                true,
                true,
                true,
                AuthorityUtils.createAuthorityList("USER"));
    }
}

这是Spring Security的第三个配置文件:

@EnableWebSecurity
@Configuration
public class WebConfiguration extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // allow everyone to register an account; /console is just for testing
        http
            .authorizeRequests()
                .antMatchers("/register", "/console/**").permitAll();

        http
            .authorizeRequests()
                .anyRequest().fullyAuthenticated();

        // making H2 console working
        http
            .headers()
                .frameOptions().disable();

        /*
        https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#when-to-use-csrf-protection
        for non-browser APIs there is no need to use csrf protection
        */
        http
            .csrf().disable();
    }
}

那我怎么解决这个问题呢?这有什么问题?为什么它无法自动装配UserAuthService

1 个答案:

答案 0 :(得分:1)

尝试更改代码以注入接口,而不是实现。这是一个交易代理。

private UserDetailsService userAuthService;

@Autowired
public AccountConfiguration(UserDetailsService userAuthService) {
    this.userAuthService = userAuthService;
}

Spring Autowiring class vs. interface?