diff --git a/server/src/main/webapp/WEB-INF/web.xml b/server/src/main/webapp/WEB-INF/web.xml
index 117c014fef..6f04261da3 100755
--- a/server/src/main/webapp/WEB-INF/web.xml
+++ b/server/src/main/webapp/WEB-INF/web.xml
@@ -20,7 +20,11 @@
1
true
-
+
+
+ org.keycloak.services.listeners.KeycloakSessionDestroyListener
+
+
index.html
diff --git a/services/src/main/java/org/keycloak/services/listeners/KeycloakSessionDestroyListener.java b/services/src/main/java/org/keycloak/services/listeners/KeycloakSessionDestroyListener.java
new file mode 100644
index 0000000000..456889fc39
--- /dev/null
+++ b/services/src/main/java/org/keycloak/services/listeners/KeycloakSessionDestroyListener.java
@@ -0,0 +1,25 @@
+package org.keycloak.services.listeners;
+
+import org.keycloak.models.KeycloakSessionFactory;
+
+import javax.servlet.ServletContextEvent;
+import javax.servlet.ServletContextListener;
+
+/**
+ * @author Stian Thorgersen
+ */
+public class KeycloakSessionDestroyListener implements ServletContextListener {
+
+ @Override
+ public void contextInitialized(ServletContextEvent sce) {
+ }
+
+ @Override
+ public void contextDestroyed(ServletContextEvent sce) {
+ KeycloakSessionFactory factory = (KeycloakSessionFactory) sce.getServletContext().getAttribute(KeycloakSessionFactory.class.getName());
+ if (factory != null) {
+ factory.close();
+ }
+ }
+
+}
diff --git a/services/src/main/java/org/keycloak/services/resources/KeycloakApplication.java b/services/src/main/java/org/keycloak/services/resources/KeycloakApplication.java
index 01e3b453a7..c7945bd9b4 100755
--- a/services/src/main/java/org/keycloak/services/resources/KeycloakApplication.java
+++ b/services/src/main/java/org/keycloak/services/resources/KeycloakApplication.java
@@ -83,11 +83,6 @@ public class KeycloakApplication extends Application {
return factory;
}
- @PreDestroy
- public void destroy() {
- factory.close();
- }
-
@Override
public Set> getClasses() {
return classes;