Почему возникает зацикливание бинов
Я пытаюсь реализовать маленький сервер для магазина товаров, но у меня возникла ошибка, делаю все по туториалу, поэтому никак не могу понять возникновение зацикленности. Может у меня глаз замылился и я не вижу бревна. Буду рад любой подсказке. Спасибо!
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private UserService userService;
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Basic
private AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
auth.setUserDetailsService(userService);
auth.setPasswordEncoder(passwordEncoder());
return auth;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/product/edit").hasAuthority(Role.ADMIN.name())
// .antMatchers("/product/edit").hasAuthority(Role.ORGANIZACION.name())
// .antMatchers("/order").hasRole(Role.CLIENT.name())
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/auth")
.permitAll()
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/").deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.and()
.csrf().disable();
}
}
public interface UserService extends UserDetailsService {//security
boolean save(UserDTO userDTO);
}
@Service
public class UserServiceImpl implements UserService{
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public UserServiceImpl(UserRepository userRepository, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
@Override
public boolean save(UserDTO userDto) {
if(!Objects.equals(userDto.getPassword(), userDto.getMatchingPassword())){
throw new RuntimeException("Password is not equal");
}
User user = User.builder()
.usernames(userDto.getUsername())
.password(passwordEncoder.encode(userDto.getPassword()))
.email(userDto.getEmail())
.role(Role.CLIENT)
.build();
userRepository.save(user);
return true;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findFirstByUsernames(username);
if(user == null){
throw new UsernameNotFoundException("User not found with name: " + username);
}
List<GrantedAuthority> roles = new ArrayList<>();
roles.add(new SimpleGrantedAuthority(user.getRole().name()));
return new org.springframework.security.core.userdetails.User(
user.getUsernames(),
user.getPassword(),
roles);
}
}
Ошибка
org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'securityConfiguration': Requested bean is currently in creation: Is there an unresolvable circular reference?
2023-03-27T01:07:18.156+03:00 ERROR 4484 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
The dependencies of some of the beans in the application context form a cycle:
???????
| securityConfiguration
? ?
| userServiceImpl defined in file [C:\Users\amir1\IdeaProjects\bridge-web\project\TestTask\target\classes\com\example\testtask\service\UserServiceImpl.class]
???????
Action:
Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.
Источник: Stack Overflow на русском