View Javadoc

1   /**
2    * Copyright 2005-2012 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.rice.core.util;
17  
18  import org.apache.log4j.Logger;
19  import org.kuali.rice.core.framework.util.ApplicationThreadLocal;
20  import org.springframework.beans.BeansException;
21  import org.springframework.context.ApplicationContext;
22  import org.springframework.context.ApplicationContextAware;
23  import org.springframework.context.ApplicationListener;
24  import org.springframework.context.ConfigurableApplicationContext;
25  import org.springframework.context.event.ContextClosedEvent;
26  
27  /**
28   * Bean which registers a listener that removes {@link ApplicationThreadLocal}s on context destruction.
29   */
30  public class ApplicationThreadLocalCleaner implements ApplicationContextAware {
31      private static final Logger LOG = Logger.getLogger(ApplicationThreadLocalCleaner.class);
32      
33      @Override
34      public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
35          // register a context close handler
36          if (applicationContext instanceof ConfigurableApplicationContext) {
37              ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext;
38              context.addApplicationListener(new ApplicationListener<ContextClosedEvent>() {
39                  @Override
40                  public void onApplicationEvent(ContextClosedEvent e) {
41                      LOG.info("Context '" + e.getApplicationContext().getDisplayName() + "' closed, removing registered ApplicationThreadLocals");
42                      if (!ApplicationThreadLocal.clear()) {
43                          LOG.error("Error(s) occurred removing registered ApplicationThreadLocals");
44                      }
45                  }
46              });
47          }
48      }
49  }