In my project I started using Spring Boot Actuator. I use /shutdown
endpoint to gracefully stop the embedded Tomcat (this works well), but I also need to do some custom logic during shutdown. Is there any way, how to do it?
I can think of two ways to perform some logic before shutting down the application:
Filter
, it's a web application after all.invoke
method using the @Before
adviceSince /shutdown
is a Servlet endpoint, you can register a Filter
to run before the /shutdown
endpoint gets called:
public class ShutdownFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain)
throws ServletException, IOException {
// Put your logic here
filterChain.doFilter(request, response);
}
}
Also don't forget to register it:
@Bean
@ConditionalOnProperty(value = "endpoints.shutdown.enabled", havingValue = "true")
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new ShutdownFilter());
registrationBean.setUrlPatterns(Collections.singleton("/shutdown"));
return registrationBean;
}
@Aspect
If you send a request to the /shutdown
endpoint, assuming the shutdown endpoint is enabled and security does not block the request, the invoke
method will be called. You can define an @Aspect
to intercept this method call and put your logic there:
@Aspect
@Component
public class ShutdownAspect {
@Before("execution(* org.springframework.boot.actuate.endpoint.ShutdownEndpoint.invoke())")
public void runBeforeShutdownHook() {
// Put your logic here
System.out.println("Going to shutdown...");
}
}
Also don't forget to enable the AspectJAutoProxy
:
@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class Application { ... }
And spring-aspects
dependency:
compile 'org.springframework:spring-aspects'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With