Can a spring boot @RestController be enabled/disabled using properties?

后端 未结 4 882
别那么骄傲
别那么骄傲 2020-12-01 01:42

Given a \"standard\" spring boot application with a @RestController, eg

@RestController
@RequestMapping(value = \"foo\", produces = \"applicatio         


        
4条回答
  •  醉梦人生
    2020-12-01 02:23

    In some case, the @ConditionalOnXXX cannot work, for example, depends on another bean instance to check condition. (XXXCondition class cannot invoke a bean).

    In such case, register controller in Java configuration file.

    See source code(Spring webmvc 5.1.6):

    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.isHandler(Class)

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

    Should add @RequestMapping annotation on type level for the controller bean. See:

    @RequestMapping // Make Spring treat the bean as request hanlder
    public class MyControllerA {
        @RequestMapping(path = { "/path1" })
        public .. restMethod1(...) {
      ........
        }
    }
    
    @RequestMapping // Make Spring treat the bean as request hanlder
    public class MyControllerB {
        @RequestMapping(path = { "/path1" })
        public .. restMethod1(...) {
      ........
        }
    }
    
    @Configuration
    public class ControllerConfiguration {
    
        /**
         *
         * Programmingly register Controller based on certain condition.
         *
         */
        @Bean
        public IMyController myController() {
            IMyController controller;
            if (conditionA) {
                cntroller = new MyControllerA();
            } else {
                controller = new MyControllerB();
            }
            return controller;
        }
    }
    

提交回复
热议问题