Home > Back-end >  Spring ConditionalOnBean does not detect bean of type RestController
Spring ConditionalOnBean does not detect bean of type RestController

Time:01-27

I have Spring boot app and I create my own autoconfiguration that should create bean in case any RestController in present in the context.

It looks something like that:

@AutoConfiguration
@ConditionalOnBean(RestController.class)
public class MyCustomAutoConfiguration {

  @Bean
  public MyBean myBean(){
    // code to create my bean
  }
}

I did defined class annotated with @RestController and I it works when I access it . But my AutoConfiguration doesn't kick in . I get the following:

condition":"OnBeanCondition","message":"@ConditionalOnBean (types: org.springframework.web.bind.annotation.RestController; SearchStrategy: all) did not find any beans of type org.springframework.web.bind.annotation.RestController"}],"matched":[]}

As far as I know Autoconfiguration is done AFTER component scanning detected bean of type restcontroller..so why it didn't pick mine?

CodePudding user response:

@CodnitionalOnBean checks that the bean of provided class is present in the current ApplicationContext. If you annotate any class, say class ABC, with @RestController or whatever annotation you want, the original class of the bean will be ABC (I say original because likely spring will wrap you bean with some Proxy, which is completely another topic), so the condition inside the @CodnitionalOnBean is not satisfied.

If you need to create some configuration beans in case you have a specific controller, then just annotate this configuration class with @CodnitionalOnBean(<YOUR CONTROLLER CLASS NAME, NOT THE ANNOTATION NAME>.class)

  • Related