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!