ConditionalOnBean without creating own config for every bean

I got a @Configuration that creates a bean, lets say Mandatory, when a specific property is set. This bean is used by many other beans that are on other files and won't work without given bean. So I tried to add @ConditionalOnBean(value = [Mandatory::class]) on the classes that will need that bean. But that does not seem to work. The condition only worked when I created the beans manually inside of the same configuration.

Am I doing something wrong or do I really need to manually create all beans, when I wanna work with conditions?

@Configuration
class MyConfig() {
  @Bean
  @ConditionalOnProperty(["my.property.activate"])
  fun mandatory(): Mandatory {
    return Mandatory()
  }

  // This works
  @Bean
  @ConditionalOnBean(value = [Mandatory::class])
  fun someClass(mandatory: Mandatory): SomeClass {
    return SomeClass(mandatory)
  }
}


// This does not work
@Component
@ConditionalOnBean([Mandatory::class])
class SomeClass(var mandatory: Mandatory) {
  //...
}
Was this page helpful?