有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法自动连接Spring安全实现类

我正在尝试为我的REST API制作BasicAuth,这是我的问题

账户配置

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

事实上,J告诉我

Could not autowire. No beans of "UserAuthService type found

但我在同一个包里有这个豆子,在这里:

@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) 个答案

  1. # 1 楼答案

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

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

    Spring Autowiring class vs. interface?