0

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?

Toni
  • 3,296
  • 2
  • 13
  • 34
user1409534
  • 2,140
  • 4
  • 27
  • 33
  • 4
    If you annotate your controller class with `@RestController` it doesn't mean it's the bean of type `RestController`. – Toni Jan 26 '23 at 10:07

1 Answers1

1

@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)

Mikhail2048
  • 1,715
  • 1
  • 9
  • 26
  • Thanx. So I can I detected if any class is annotated with @RestController within mu autoconfiguration file? – user1409534 Jan 26 '23 at 18:50
  • 1
    You can ask `ApplicationContext` to do it, just use `ApplicationContext.getBeansWithAnnotation(RestController.class)` – Mikhail2048 Jan 27 '23 at 06:10