001 /**
002 * Copyright 2005-2014 The Kuali Foundation
003 *
004 * Licensed under the Educational Community License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.opensource.org/licenses/ecl2.php
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016 package org.kuali.rice.core.util;
017
018 import org.apache.log4j.Logger;
019 import org.kuali.rice.core.framework.util.ApplicationThreadLocal;
020 import org.springframework.beans.BeansException;
021 import org.springframework.context.ApplicationContext;
022 import org.springframework.context.ApplicationContextAware;
023 import org.springframework.context.ApplicationListener;
024 import org.springframework.context.ConfigurableApplicationContext;
025 import org.springframework.context.event.ContextClosedEvent;
026
027 /**
028 * Bean which registers a listener that removes {@link ApplicationThreadLocal}s on context destruction.
029 */
030 public class ApplicationThreadLocalCleaner implements ApplicationContextAware {
031 private static final Logger LOG = Logger.getLogger(ApplicationThreadLocalCleaner.class);
032
033 @Override
034 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
035 // register a context close handler
036 if (applicationContext instanceof ConfigurableApplicationContext) {
037 ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext;
038 context.addApplicationListener(new ApplicationListener<ContextClosedEvent>() {
039 @Override
040 public void onApplicationEvent(ContextClosedEvent e) {
041 LOG.info("Context '" + e.getApplicationContext().getDisplayName() + "' closed, removing registered ApplicationThreadLocals");
042 if (!ApplicationThreadLocal.clear()) {
043 LOG.error("Error(s) occurred removing registered ApplicationThreadLocals");
044 }
045 }
046 });
047 }
048 }
049 }