gpt4 book ai didi

java - 无法 Autowiring Spring Security 实现类

转载 作者:行者123 更新时间:2023-12-01 08:57:16 24 4
gpt4 key购买 nike

我正在尝试为我的 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);
}
}

在构造函数中 IntelliJ 告诉我

Could not autowire. No beans of "UserAuthService type found

但我在同一个包中有那个 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();
}
}

那么我该如何解决这个问题呢?这里有什么问题?为什么它无法 Autowiring UserAuthService

最佳答案

尝试更改代码以注入(inject)接口(interface),而不是实现。它是一个事务代理。

private UserDetailsService userAuthService;

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

Spring Autowiring class vs. interface?

关于java - 无法 Autowiring Spring Security 实现类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41968509/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com