|
| 1 | +/* |
| 2 | + * Copyright 2012-2015 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 |
| 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 | + |
| 17 | +package org.springframework.boot; |
| 18 | + |
| 19 | +import java.lang.reflect.Method; |
| 20 | + |
| 21 | +import org.springframework.context.ApplicationListener; |
| 22 | +import org.springframework.context.event.ContextRefreshedEvent; |
| 23 | +import org.springframework.util.ReflectionUtils; |
| 24 | + |
| 25 | +/** |
| 26 | + * {@link ApplicationListener} to cleanup caches once the context is loaded. |
| 27 | + * |
| 28 | + * @author Phillip Webb |
| 29 | + */ |
| 30 | +class ClearCachesApplicationListener |
| 31 | + implements ApplicationListener<ContextRefreshedEvent> { |
| 32 | + |
| 33 | + @Override |
| 34 | + public void onApplicationEvent(ContextRefreshedEvent event) { |
| 35 | + ReflectionUtils.clearCache(); |
| 36 | + clearClassLoaderCaches(Thread.currentThread().getContextClassLoader()); |
| 37 | + } |
| 38 | + |
| 39 | + private void clearClassLoaderCaches(ClassLoader classLoader) { |
| 40 | + if (classLoader == null) { |
| 41 | + return; |
| 42 | + } |
| 43 | + try { |
| 44 | + Method clearCacheMethod = classLoader.getClass() |
| 45 | + .getDeclaredMethod("clearCache"); |
| 46 | + clearCacheMethod.invoke(classLoader); |
| 47 | + } |
| 48 | + catch (Exception ex) { |
| 49 | + // Ignore |
| 50 | + } |
| 51 | + clearClassLoaderCaches(classLoader.getParent()); |
| 52 | + } |
| 53 | + |
| 54 | +} |
0 commit comments