Spring – Order of Bean-Creation defined in Security-Configurations

In a Spring-Boot and Spring-Security application, I have two Security-Configurations. So two classes that are annotated with @Configuration and
@EnableWebSecurity and extending WebSecurityConfigurerAdapter.

In Configuration one, let’s just call it foo, I create two beans (annotated with @Bean). Both beans are AuthenticationProvider’s. One of them is marked with @Primary and @ConditionalOnProperty. It replaces the other authentication provider if some property is set, for testing purposes.

In the other Configuration, let’s call it bar, I request one of these AuthenticationProviders by having an @Autowired annotated field of type AuthenticationProvider.

I have annotated the foo-Configuration with @Order(1) to indicate that it should run first. bar-Configuration has @Order(2). However, the application cannot start this way. Spring tells me that it cannot create the bar-configuration because the requested AuthenticationProvider-bean is still under creation. This confuses me. I thought the the foo-Configuration should already have been created, because it has a higher Order-priority? Why is the bean still not available?

If I annotate the bar-Configuration with @DependsOn("fooConfiguration")then it works. But I don’t really understand why. Also: Is the usage of @DependsOn code-smell and is what I am doing unorthodox (injecting a bean of one configuration into another)?

Leave a Reply

avatar
  Subscribe  
Notify of