Home > Back-end >  circular dependency in web application using spring boot security
circular dependency in web application using spring boot security

Time:04-14

Circular dependency error. As I'm new to this technology i couldn't solve this. i need some here to clear this issue. This code is to secure few pages in the existing project. I have to secure only 3 pages to access only by admin. Any solution which can escape circular dependency or which can fulfil my task will help. My task is to complete secure few pages from accessing the user. This code is taken from a stackoverflow snippet.

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/editincident","editaccident","editreqeust").authenticated()
                .anyRequest().permitAll()
                .and()
                .csrf().disable();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }
}

error message

CodePudding user response:

I also faced the same issue while working on one of the projects. Just add one line in your application.properties file.

spring.main.allow-circular-references=true

this might solve your problem.

CodePudding user response:

Include this line in your application.properties file :

spring.main.allow-circular-references=true

CodePudding user response:

In spring.io docs there is "If you use predominantly constructor injection, it is possible to create an unresolvable circular dependency scenario.

For example: Class A requires an instance of class B through constructor injection, and class B requires an instance of class A through constructor injection. If you configure beans for classes A and B to be injected into each other, the Spring IoC container detects this circular reference at runtime, and throws a BeanCurrentlyInCreationException.

One possible solution is to edit the source code of some classes to be configured by setters rather than constructors. Alternatively, avoid constructor injection and use setter injection only. In other words, although it is not recommended, you can configure circular dependencies with setter injection."

So you should change the way you create one of your beans with using constructor method

  • Related