Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fmarot/1606f0427a700dcbdcf4e87bc457fbd8 to your computer and use it in GitHub Desktop.
Save fmarot/1606f0427a700dcbdcf4e87bc457fbd8 to your computer and use it in GitHub Desktop.
workaround for spring context re-creating itself when closing after a JUnit test class annotated @SpringBootTest has run
import javax.servlet.http.HttpSessionEvent;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.security.web.session.HttpSessionEventPublisher;
/** This class workaround a bug we observed in JUnit tests when using a full- sds server in AbstractRealDatamanagerTest:
* the problem was that when the spring context was trying to close, then tomcat was finally closed triggering a
* 'sessionDestroyed' event that in turn tried to publish a 'sessionDestroyed' having the effect of reviving the context.
* Have you seen The Walking Dead ? It was kinda similar... */
public class HttpSessionEventPublisherWithcontextDoesNotStopWorkaround extends HttpSessionEventPublisher {
private boolean contextIsStarted = false;
@Override
public void sessionCreated(HttpSessionEvent event) {
if (contextIsStarted) {
sessionCreated(event);
}
}
@Override
public void sessionDestroyed(HttpSessionEvent event) {
if (contextIsStarted) {
sessionDestroyed(event);
}
}
@EventListener
public void onContextClosed(ContextClosedEvent contextClosed) {
contextIsStarted = false;
}
@EventListener
public void onContextClosed(ContextStartedEvent contextStarted) {
contextIsStarted = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment