InitDestroyAnnotationBeanPostProcessor.java 12.6 KB
Newer Older
1
/*
2
 * Copyright 2002-2011 the original author or authors.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.beans.factory.annotation;

19 20
import java.io.IOException;
import java.io.ObjectInputStream;
21 22 23 24
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
25
import java.lang.reflect.Modifier;
26
import java.util.Collection;
27
import java.util.Collections;
28
import java.util.Iterator;
29
import java.util.LinkedHashSet;
30
import java.util.LinkedList;
31
import java.util.Map;
32
import java.util.Set;
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.util.ReflectionUtils;

/**
 * {@link org.springframework.beans.factory.config.BeanPostProcessor} implementation
 * that invokes annotated init and destroy methods. Allows for an annotation
 * alternative to Spring's {@link org.springframework.beans.factory.InitializingBean}
 * and {@link org.springframework.beans.factory.DisposableBean} callback interfaces.
 *
 * <p>The actual annotation types that this post-processor checks for can be
 * configured through the {@link #setInitAnnotationType "initAnnotationType"}
 * and {@link #setDestroyAnnotationType "destroyAnnotationType"} properties.
 * Any custom annotation can be used, since there are no required annotation
 * attributes.
 *
 * <p>Init and destroy annotations may be applied to methods of any visibility:
 * public, package-protected, protected, or private. Multiple such methods
 * may be annotated, but it is recommended to only annotate one single
 * init method and destroy method, respectively.
 *
 * <p>Spring's {@link org.springframework.context.annotation.CommonAnnotationBeanPostProcessor}
 * supports the JSR-250 {@link javax.annotation.PostConstruct} and {@link javax.annotation.PreDestroy}
 * annotations out of the box, as init annotation and destroy annotation, respectively.
 * Furthermore, it also supports the {@link javax.annotation.Resource} annotation
 * for annotation-driven injection of named beans.
 *
 * @author Juergen Hoeller
 * @since 2.5
 * @see #setInitAnnotationType
 * @see #setDestroyAnnotationType
 */
75
@SuppressWarnings("serial")
76 77 78
public class InitDestroyAnnotationBeanPostProcessor
		implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable {

79
	protected transient Log logger = LogFactory.getLog(getClass());
80 81 82 83 84

	private Class<? extends Annotation> initAnnotationType;

	private Class<? extends Annotation> destroyAnnotationType;

J
Juergen Hoeller 已提交
85
	private int order = Ordered.LOWEST_PRECEDENCE;
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121

	private transient final Map<Class<?>, LifecycleMetadata> lifecycleMetadataCache =
			new ConcurrentHashMap<Class<?>, LifecycleMetadata>();


	/**
	 * Specify the init annotation to check for, indicating initialization
	 * methods to call after configuration of a bean.
	 * <p>Any custom annotation can be used, since there are no required
	 * annotation attributes. There is no default, although a typical choice
	 * is the JSR-250 {@link javax.annotation.PostConstruct} annotation.
	 */
	public void setInitAnnotationType(Class<? extends Annotation> initAnnotationType) {
		this.initAnnotationType = initAnnotationType;
	}

	/**
	 * Specify the destroy annotation to check for, indicating destruction
	 * methods to call when the context is shutting down.
	 * <p>Any custom annotation can be used, since there are no required
	 * annotation attributes. There is no default, although a typical choice
	 * is the JSR-250 {@link javax.annotation.PreDestroy} annotation.
	 */
	public void setDestroyAnnotationType(Class<? extends Annotation> destroyAnnotationType) {
		this.destroyAnnotationType = destroyAnnotationType;
	}

	public void setOrder(int order) {
	  this.order = order;
	}

	public int getOrder() {
	  return this.order;
	}


122
	public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
123 124
		if (beanType != null) {
			LifecycleMetadata metadata = findLifecycleMetadata(beanType);
125
			metadata.checkConfigMembers(beanDefinition);
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
		}
	}

	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
		try {
			metadata.invokeInitMethods(bean, beanName);
		}
		catch (InvocationTargetException ex) {
			throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());
		}
		catch (Throwable ex) {
			throw new BeanCreationException(beanName, "Couldn't invoke init method", ex);
		}
		return bean;
	}

	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
		LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
		try {
			metadata.invokeDestroyMethods(bean, beanName);
		}
		catch (InvocationTargetException ex) {
			String msg = "Invocation of destroy method failed on bean with name '" + beanName + "'";
			if (logger.isDebugEnabled()) {
				logger.warn(msg, ex.getTargetException());
			}
			else {
				logger.warn(msg + ": " + ex.getTargetException());
			}
		}
		catch (Throwable ex) {
			logger.error("Couldn't invoke destroy method on bean with name '" + beanName + "'", ex);
		}
	}


167
	private LifecycleMetadata findLifecycleMetadata(Class<?> clazz) {
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
		if (this.lifecycleMetadataCache == null) {
			// Happens after deserialization, during destruction...
			return buildLifecycleMetadata(clazz);
		}
		// Quick check on the concurrent map first, with minimal locking.
		LifecycleMetadata metadata = this.lifecycleMetadataCache.get(clazz);
		if (metadata == null) {
			synchronized (this.lifecycleMetadataCache) {
				metadata = this.lifecycleMetadataCache.get(clazz);
				if (metadata == null) {
					metadata = buildLifecycleMetadata(clazz);
					this.lifecycleMetadataCache.put(clazz, metadata);
				}
				return metadata;
			}
		}
		return metadata;
	}

187
	private LifecycleMetadata buildLifecycleMetadata(Class<?> clazz) {
188
		final boolean debug = logger.isDebugEnabled();
189 190 191 192 193 194 195 196 197 198 199 200
		LinkedList<LifecycleElement> initMethods = new LinkedList<LifecycleElement>();
		LinkedList<LifecycleElement> destroyMethods = new LinkedList<LifecycleElement>();
		Class<?> targetClass = clazz;

		do {
			LinkedList<LifecycleElement> currInitMethods = new LinkedList<LifecycleElement>();
			LinkedList<LifecycleElement> currDestroyMethods = new LinkedList<LifecycleElement>();
			for (Method method : targetClass.getDeclaredMethods()) {
				if (this.initAnnotationType != null) {
					if (method.getAnnotation(this.initAnnotationType) != null) {
						LifecycleElement element = new LifecycleElement(method);
						currInitMethods.add(element);
201 202 203 204 205
						if (debug) {
							logger.debug("Found init method on class [" + clazz.getName() + "]: " + method);
						}
					}
				}
206 207 208
				if (this.destroyAnnotationType != null) {
					if (method.getAnnotation(this.destroyAnnotationType) != null) {
						currDestroyMethods.add(new LifecycleElement(method));
209 210 211 212 213 214
						if (debug) {
							logger.debug("Found destroy method on class [" + clazz.getName() + "]: " + method);
						}
					}
				}
			}
215 216 217 218 219 220 221
			initMethods.addAll(0, currInitMethods);
			destroyMethods.addAll(currDestroyMethods);
			targetClass = targetClass.getSuperclass();
		}
		while (targetClass != null && targetClass != Object.class);

		return new LifecycleMetadata(clazz, initMethods, destroyMethods);
222 223 224
	}


225 226 227 228 229 230 231 232 233 234 235 236 237
	//---------------------------------------------------------------------
	// Serialization support
	//---------------------------------------------------------------------

	private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
		// Rely on default serialization; just initialize state after deserialization.
		ois.defaultReadObject();

		// Initialize transient fields.
		this.logger = LogFactory.getLog(getClass());
	}


238 239 240 241 242
	/**
	 * Class representing information about annotated init and destroy methods.
	 */
	private class LifecycleMetadata {

243 244 245 246
		private final Set<LifecycleElement> initMethods;

		private final Set<LifecycleElement> destroyMethods;

247
		public LifecycleMetadata(Class<?> targetClass, Collection<LifecycleElement> initMethods,
248
				Collection<LifecycleElement> destroyMethods) {
249

250
			this.initMethods = Collections.synchronizedSet(new LinkedHashSet<LifecycleElement>());
251 252 253 254 255 256
			for (LifecycleElement element : initMethods) {
				if (logger.isDebugEnabled()) {
					logger.debug("Found init method on class [" + targetClass.getName() + "]: " + element);
				}
				this.initMethods.add(element);
			}
257

258
			this.destroyMethods = Collections.synchronizedSet(new LinkedHashSet<LifecycleElement>());
259 260 261 262 263
			for (LifecycleElement element : destroyMethods) {
				if (logger.isDebugEnabled()) {
					logger.debug("Found destroy method on class [" + targetClass.getName() + "]: " + element);
				}
				this.destroyMethods.add(element);
264
			}
265 266
		}

267
		public void checkConfigMembers(RootBeanDefinition beanDefinition) {
268 269 270 271 272 273 274 275 276
			synchronized(this.initMethods) {
				for (Iterator<LifecycleElement> it = this.initMethods.iterator(); it.hasNext();) {
					String methodIdentifier = it.next().getIdentifier();
					if (!beanDefinition.isExternallyManagedInitMethod(methodIdentifier)) {
						beanDefinition.registerExternallyManagedInitMethod(methodIdentifier);
					}
					else {
						it.remove();
					}
277 278
				}
			}
279 280 281 282 283 284 285 286 287
			synchronized(this.destroyMethods) {
				for (Iterator<LifecycleElement> it = this.destroyMethods.iterator(); it.hasNext();) {
					String methodIdentifier = it.next().getIdentifier();
					if (!beanDefinition.isExternallyManagedDestroyMethod(methodIdentifier)) {
						beanDefinition.registerExternallyManagedDestroyMethod(methodIdentifier);
					}
					else {
						it.remove();
					}
288 289
				}
			}
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
		}

		public void invokeInitMethods(Object target, String beanName) throws Throwable {
			if (!this.initMethods.isEmpty()) {
				boolean debug = logger.isDebugEnabled();
				for (LifecycleElement element : this.initMethods) {
					if (debug) {
						logger.debug("Invoking init method on bean '" + beanName + "': " + element.getMethod());
					}
					element.invoke(target);
				}
			}
		}

		public void invokeDestroyMethods(Object target, String beanName) throws Throwable {
			if (!this.destroyMethods.isEmpty()) {
				boolean debug = logger.isDebugEnabled();
				for (LifecycleElement element : this.destroyMethods) {
					if (debug) {
						logger.debug("Invoking destroy method on bean '" + beanName + "': " + element.getMethod());
					}
					element.invoke(target);
				}
			}
		}
	}


	/**
	 * Class representing injection information about an annotated method.
	 */
	private static class LifecycleElement {

		private final Method method;

325 326
		private final String identifier;

327 328 329 330 331
		public LifecycleElement(Method method) {
			if (method.getParameterTypes().length != 0) {
				throw new IllegalStateException("Lifecycle method annotation requires a no-arg method: " + method);
			}
			this.method = method;
332 333
			this.identifier = (Modifier.isPrivate(method.getModifiers()) ?
					method.getDeclaringClass() + "." + method.getName() : method.getName());
334 335 336 337 338 339
		}

		public Method getMethod() {
			return this.method;
		}

340 341 342 343
		public String getIdentifier() {
			return this.identifier;
		}

344 345 346 347 348
		public void invoke(Object target) throws Throwable {
			ReflectionUtils.makeAccessible(this.method);
			this.method.invoke(target, (Object[]) null);
		}

349
		@Override
350
		public boolean equals(Object other) {
351 352 353 354 355 356 357
			if (this == other) {
				return true;
			}
			if (!(other instanceof LifecycleElement)) {
				return false;
			}
			LifecycleElement otherElement = (LifecycleElement) other;
358
			return (this.identifier.equals(otherElement.identifier));
359 360
		}

361
		@Override
362
		public int hashCode() {
363
			return this.identifier.hashCode();
364 365 366 367
		}
	}

}