Naveen Kumar
Naveen Kumar

Reputation: 65

circular dependency in web application using spring boot security

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

Upvotes: 0

Views: 4318

Answers (2)

rg226965
rg226965

Reputation: 59

you can write one line in your application.properties file to remove this error.
spring.main.allow-circular-references= true

Upvotes: 1

Дима Шуть
Дима Шуть

Reputation: 31

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

Upvotes: 2

Related Questions