Search code examples
springspring-bootspring-restcontrollerspring-autoconfiguration

AutoConfigure RestController Spring Boot


I have tried to find documentation on how to manually configure a RestController (i.e in a Configuation class). That means without using the RestController annotation. Considering all the other annotations, like mapping, pathvariables etc. is at all possible?


Solution

  • A controller is essentially a component with a request mapping. See RequestMappingHandlerMapping.

        @Override
        protected boolean isHandler(Class<?> beanType) {
            return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||
                    AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class));
        }
    

    If you want to instantiate a "rest controller" through configuration, you can probably do so via the following:

    @Configuration
    public class MyConfiguration {
       @Bean
       public MyController() {
          return new MyController();
       }
    }
    
    @ResponseBody
    public class MyController {
       @RequestMapping("/test")
       public String someEndpoint() {
          return "some payload";
       }
    }
    

    But I don't think you'll be able to configure the request mappings (path variables, etc) in the configuration though; at least I haven't seen an example nor figured out how.