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

后端 未结 4 883
别那么骄傲
别那么骄傲 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:22

    Adding to this question and another question here.

    This is my answer:

    I would actually used the @RefreshScope Bean and then when you want to stop the Rest Controller at runtime, you only need to change the property of said controller to false.

    SO's link referencing to changing property at runtime.

    Here are my snippets of working code:

    @RefreshScope
    @RestController
    class MessageRestController(
        @Value("\${message.get.enabled}") val getEnabled: Boolean,
        @Value("\${message:Hello default}") val message: String
    ) {
        @GetMapping("/message")
        fun get(): String {
            if (!getEnabled) {
                throw NoHandlerFoundException("GET", "/message", null)
            }
            return message
        }
    }
    

    And there are other alternatives of using Filter:

    @Component
    class EndpointsAvailabilityFilter @Autowired constructor(
        private val env: Environment
    ): OncePerRequestFilter() {
        override fun doFilterInternal(
            request: HttpServletRequest,
            response: HttpServletResponse,
            filterChain: FilterChain
        ) {
            val requestURI = request.requestURI
            val requestMethod = request.method
            val property = "${requestURI.substring(1).replace("/", ".")}." +
                    "${requestMethod.toLowerCase()}.enabled"
            val enabled = env.getProperty(property, "true")
            if (!enabled.toBoolean()) {
                throw NoHandlerFoundException(requestMethod, requestURI, ServletServerHttpRequest(request).headers)
            }
            filterChain.doFilter(request, response)
        }
    }
    

    My Github explaining how to disable at runtime

提交回复
热议问题