title: Spring Security: The dependencies of some of the beans in the application context form a cycle
body: <p>I want to configure Spring Security for a project.</p>
  
  <p>However, it fails with next error:</p>
  
  <pre><code>***************************
  APPLICATION FAILED TO START
  ***************************    
  Description:    
  The dependencies of some of the beans in the application context form a cycle:    
  ┌─────┐
  |  securityConfiguration defined in file [C:\Users\Nazar\Projects\IdeaProjects\Lohika_Projects\blog\target\classes\net\lelyak\edu\configuration\SecurityConfiguration.class]
  ↑     ↓
  |  blogDTS defined in file [C:\Users\Nazar\Projects\IdeaProjects\Lohika_Projects\blog\target\classes\net\lelyak\edu\rest\service\impl\UserDetailsServiceImpl.class]
  ↑     ↓
  |  userServiceImpl defined in file [C:\Users\Nazar\Projects\IdeaProjects\Lohika_Projects\blog\target\classes\net\lelyak\edu\rest\service\impl\UserServiceImpl.class]
  └─────┘
  </code></pre>
  
  <p>Next, you can see my spring security configuration:</p>
  
  <pre><code>@Configuration
  @AllArgsConstructor
  public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
      private DataSource dataSource;
      @Qualifier("blogDTS")
      private UserDetailsService userDetailsService;
      private AccessDeniedHandler accessDeniedHandler;
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http.csrf().disable()
                  .authorizeRequests()
                  .antMatchers("/", "/registration", "/403", "/500").permitAll()
                  .antMatchers("/posts/**").hasAnyRole("USER")
                  .antMatchers("/post/**").hasAnyRole("USER")
                  .anyRequest().authenticated()
                  .and()
                  .formLogin().loginPage("/login").permitAll()
                  .usernameParameter("username")
                  .passwordParameter("password")
                  .defaultSuccessUrl("/posts")
                  .and()
                  .rememberMe().tokenValiditySeconds(10_000).tokenRepository(persistentTokenRepository())
                  .and()
                  .logout().permitAll()
                  .and()
                  .exceptionHandling().accessDeniedHandler(accessDeniedHandler).accessDeniedPage("/403");
      }
  
      @Autowired
      public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
          auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
      }
  
      @Bean
      public PasswordEncoder passwordEncoder() {
          return new BCryptPasswordEncoder();
      }
  
      @Override
      protected UserDetailsService userDetailsService() {
          return userDetailsService;
      }
  
      @Bean
      public PersistentTokenRepository persistentTokenRepository() {
          JdbcTokenRepositoryImpl db = new JdbcTokenRepositoryImpl();
          db.setDataSource(dataSource);
          return db;
      }
  
      @Bean
      public SavedRequestAwareAuthenticationSuccessHandler
      savedRequestAwareAuthenticationSuccessHandler() {
          SavedRequestAwareAuthenticationSuccessHandler auth
                  = new SavedRequestAwareAuthenticationSuccessHandler();
          auth.setTargetUrlParameter("targetUrl");
          return auth;
      }
  }
  </code></pre>
  
  <p><code>UserDetailsServiceImpl</code> code snippet:</p>
  
  <pre><code>@Service("blogDTS")
  @AllArgsConstructor
  public class UserDetailsServiceImpl implements UserDetailsService {
      private UserServiceImpl userService;
  
      @Override
      public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
  
          BlogUser user = userService.getUser(username);
          List&lt;GrantedAuthority&gt; authorities = buildUserAuthority(user.getRole());
  
          return buildUserForAuthentication(user, authorities);
  
      }
  
      private org.springframework.security.core.userdetails.User buildUserForAuthentication(BlogUser user,
                                                                                            List&lt;GrantedAuthority&gt; authorities) {
          return new org.springframework.security.core.userdetails.User(
                  user.getUserName(),
                  user.getPassword(),
                  user.isEnabled(),
                  true,
                  true,
                  true,
                  authorities);
      }
  
      private List&lt;GrantedAuthority&gt; buildUserAuthority(Role userRole) {
          Set&lt;GrantedAuthority&gt; setAuths = Stream.of(new SimpleGrantedAuthority(userRole.name()))
                  .collect(Collectors.toSet());
          return Lists.newArrayList(setAuths);
      }
  }
  </code></pre>
  
  <p><code>UserServiceImpl</code> is usual Service layer which manages Repository operations:</p>
  
  <pre><code>@Service
  @AllArgsConstructor
  public class UserServiceImpl implements UserService {
      private final UserRepository userRepository;
      private final PasswordEncoder passwordEncoder;
  
      @Override
      public List&lt;BlogUser&gt; getAllUsers() {
          List&lt;BlogUser&gt; result = new ArrayList&lt;&gt;();
          result.addAll(userRepository.findAll());
          return result;
      }
  
      @Override
      public BlogUser getUser(String userName) {
          Assert.hasText(userName, "User name is empty");
          return userRepository.findByUserName(userName)
                  .orElseThrow(() -&gt; new NotPresentedInDbException(userName));
      }
  </code></pre>
  
  <p>I can't understand how to solve this circular issue with Spring Security.</p>
  
  <p><strong><em>How to solve this issue?</em></strong></p>