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.
Asked
Active
Viewed 1,253 times
0
-
Hm, since every @Controller is a regular bean I can probably destroy it like every other bean by retrieving it from the context as `DefaultListableBeanFactory` and call `destroySingleton()` with the bean's name. – Andras Hatvani Dec 17 '18 at 13:02
-
Why do you need to destroy it? You could also return a 404 with an if (certain circunstance) ... – Juan Dec 17 '18 at 19:38
1 Answers
2
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)
}
}

David Latief Budiman
- 135
- 1
- 7