我发现Can a spring boot @RestController be enabled/disabled using properties?解决了启动时未启动@Controller的问题,但我正在寻找一种在运行时停止@Controller的方法。
答案 0 :(得分:0)
我实际上会使用@RefreshScope Bean,然后当您想在运行时停止Rest Controller时,只需要将该控制器的属性更改为false。
SO的link引用运行时更改的属性。
以下是我的工作代码段:
@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
}
}
还有使用过滤器的其他替代方法:
@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)
}
}