本文介绍了在运行时停止 Spring @Controller的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 可以使用属性启用/禁用 spring boot @RestController 吗? 哪个地址没有在以下位置启动 @Controller启动时间,但我正在寻找一种在运行时停止 @Controller 的方法.

I've found Can a spring boot @RestController be enabled/disabled using properties? which addresses not starting a @Controller at boot time, but I'm looking for a way to stop a @Controller at runtime.

推荐答案

我实际上会使用@RefreshScope Bean,然后当您想在运行时停止 Rest Controller 时,您只需要将所述控制器的属性更改为 false.

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 的 link 引用了在运行时更改属性.

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

我的 Github 解释了如何在运行时禁用

这篇关于在运行时停止 Spring @Controller的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 09:20