Cannot call consturctor of WebSecurityConfigurerAdapter when using @Order

Viewed 32

I have a library that contains the class QuerySecurityConfig extends WebSecurityConfigurerAdapter for implementing Web-Security. A stripped-down version of this security config class is as follows:

@Configuration
@EnableWebSecurity
@Order(101)
public class QuerySecurityConfig extends WebSecurityConfigurerAdapter {
    public QuerySecurityConfig(){
        ...
        this(Arrays.asList("/v2/api-docs");
    }
    
    public QuerySecurityConfig(List<String> ignoredRestEndPoints){
        ...
        this.ignoredRestEndPoints = ignoredRestEndPoints;
    }

    public QuerySecurityConfig(List<String> ignoredRestEndPoints) {
        this();
        this.ignoredRestEndPoints.addAll(ignoredRestEndPoints);
    }

    @Override
    public void configure(WebSecurity web){
        web.ignoring().antMatchers(this.ignoredRestEndpoints.toArray(new String[0]));
    }
}

Now, I am trying to instantiate a Bean of this security class using one of the constructors as follows

@Bean
@Order(200)
public QuerySecurityConfig getQuerySecurityConfig() {
    List<String> excludedEndpoints = new ArrayList<>();
    excludedEndpoints.add("/seller/**");
    return new QuerySecurityConfig(excludedEndpoints);
}

However, I keep running into the following error:

Caused by: java.lang.IllegalStateException: @Order on WebSecurityConfigurers must be unique. Order of 101 was already used on com.example.app.security.QuerySecurityConfig$$
EnhancerBySpringCGLIB$$ca9e6a6c@4981b83, so it cannot be used on com.example.app.security.QuerySecurityConfig@2e549515 too.

How can I invoke the constructor on such a class when @Order is present?

1 Answers

It appears that I am attempting to create two Beans of the QuerySecurityConfig class. The first bean is being created due to the @Configuration annotation over QuerySecurityConfig and the second one is being created manually by the getQuerySecurityConfig() method, annotated by @Bean. This is causing a duplication of the Order and hence the exception.

I managed to fix this by simply excluding QuerySecurityConfig from the Component-Scan. After this, I also had to add @EnableWebSecurity to my configuration class since it was being ignored along with the rest of the QuerySecurityConfig class.

Related