'Trouble with "The dependencies of some of the beans in the application context form a cycle"

I'm working on the course "Information System" and follow the operation of the prof, but it turns a strange error:

The dependencies of some of the beans in the application context form a cycle:

here's my classes:

@Service
public class UsersService implements UserDetailsService {

@Autowired
private  UsersRepository _usersDb;

@Autowired
private  BCryptPasswordEncoder _passwordEncoder;
public boolean registerNewUser(String username, String password, Role role) {
    Optional<User> oldUser = _usersDb.findByUsername(username);
    if(oldUser.isPresent()) {
        return false;
    }
    
    
    String encodedPassword = _passwordEncoder.encode(password);
    User newUser = new User(null, encodedPassword, username, role);
    
    _usersDb.save(newUser);
    return true;
}


public List<User> getAllUsers() {
    return _usersDb.findAll();
}

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Optional<User> user = _usersDb.findByUsername(username);
    
    if(!user.isPresent()) {
        throw new UsernameNotFoundException("User not found");
    }
    
    return user.get();


}

public boolean isAdminNotExists(String adminUsername) {
    return _usersDb.findAll((r, q, b) -> b.or(
            b.equal(r.get("role"), Role.ADMIN),
            b.equal(r.get("username"), adminUsername)
    )).isEmpty();
}

then:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{


@Autowired
private  UsersService _usersService;


@Override
protected void configure(HttpSecurity httpSec) throws Exception {
    httpSec.csrf()
            .disable()
            .authorizeRequests()
                .antMatchers("/registration").not().fullyAuthenticated()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/dishes/**").hasAnyRole("USER", "MANAGER")
                .antMatchers("/", "/resources/**").permitAll()
            .anyRequest().authenticated()
            .and()
                .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/")
                .permitAll()
            .and()
                .logout()
                .permitAll()
                .logoutSuccessUrl("/");
    
}

protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(_usersService).passwordEncoder(bCryptPasswordEncoder());
}

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
    return new BCryptPasswordEncoder();
}

}

and this:

@Component
public class IsProjectAppDataInitializier implements ApplicationListener<ContextRefreshedEvent>{
    
private boolean _alreadyInitialized = false;


private final  UsersService _usersSvc;

public IsProjectAppDataInitializier(UsersService usersSvc) {
    _usersSvc = usersSvc;
}

@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    
    if(!_alreadyInitialized) {
        _alreadyInitialized = true;
        this.initializeApp();
    }
    
}

private void initializeApp() {
    if (_usersSvc.isAdminNotExists("admin")) {
        _usersSvc.registerNewUser("admin", "password", Role.ADMIN);
    }
    
}

@Autowired works in the video of prof, but not works on mine.... Really need guys your help!



Solution 1:[1]

Your problem is same as this video tutorial I learned from. Search for the Soham Karmakar's comment. He asked this problem and below this comment it might be your solution as well.

I would tell you solution, but I can not see your UserServiceImplementation class.

Basicly your solution might be here:

  • remove private UsersRepository _usersDb; (UsersService.class)
  • change your passwordEncoder.encode(... to new BCryptPasswordEncoder().encode(.. (Your UserServiceImplementation.class)

For your WebSecurityConfig.class change

auth.userDetailsService(_usersService).passwordEncoder(bCryptPasswordEncoder());

to `

auth.userDetailsService(_usersService);
auth.setPasswordEncoder(new BCryptPasswordEncoder());

`

Try, it should work.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Khanspii