Hello! :wave: I’m hitting a problem with condition...
# spring
d
Hello! 👋 I’m hitting a problem with conditional bean creation order - I’m writing custom bean registrar to generate and register some beans based on the configuration properties and I provide some default beans as a fallback. Basically • I got an annotation for explicit opt-in where I import my registrar and fallback config • registrar is environment aware so it can bind my properties and uses factory bean to create target beans (e.g.
BeanDefinitionBuilder.genericBeanDefinition(MyFactoryBean::class.java)
MyFactoryBean
is application context aware and it attempts to retrieve
FallbackBean
from context (e.g. using
applicationContext.getBean(FallbackBean::class.java)
• within a
@SpringBootTest
I’m explicitly creating
SomeBean
in a configuration class So my problem is that conditional logic (i.e.
@ConditionalOnBean
) is evaluated BEFORE attempting to create the
SomeBean
in test configuration…. Sample code in the thread. Any ideas what I might be missing?
Copy code
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS)
@Import(MyBeanRegistrar::class, MyFallbackConfiguration::class)
@EnableConfigurationProperties(MyProperties::class)
annotation class EnableMyAutoConfiguration

@ConditionalOnBean(SomeBean::class)
@Configuration
class MyFallbackConfiguration {

    @Bean
    @ConditionalOnMissingBean
    fun fallbackBean(someBean: SomeBean): FallbackBean = DefaultFallbackBean(someBean)
}

@SpringBootTest(classes = [MyConfigurationIT.MyTestConfiguration::class])
class MyConfigurationIT {

    @Configuration
    @EnableAutoConfiguration
    @EnableMyAutoConfiguration
    class MyTestConfiguration {

        @Bean
        fun someBean(): SomeBean = SomeBean()   // <== this gets created AFTER conditional evaluation
    }

    @Test
    fun `context loads`() {
    }
}
if anyone is looking for the similar problem -> I solved the issue by making
MyFallbackConfiguration
a spring auto configuration (i.e. configuring it in
META-INF/spring.factories
and removing the explicit import from the annotation)