ApplicationListenerMethodAdapter.java 11.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 * Copyright 2002-2015 the original author or authors.
 *
 * 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.context.event;

19
import java.lang.annotation.Annotation;
20 21 22
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.UndeclaredThrowableException;
23
import java.util.Collection;
24 25 26 27 28 29 30 31 32 33

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

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.PayloadApplicationEvent;
import org.springframework.context.expression.AnnotatedElementKey;
import org.springframework.core.BridgeMethodResolver;
import org.springframework.core.ResolvableType;
34 35
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationAttributes;
36 37 38 39
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.expression.EvaluationContext;
import org.springframework.util.Assert;
40
import org.springframework.util.ObjectUtils;
41 42 43 44 45 46 47
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

/**
 * {@link GenericApplicationListener} adapter that delegates the processing of
 * an event to an {@link EventListener} annotated method.
 *
48
 * <p>Delegates to {@link #processEvent(ApplicationEvent)} to give a chance to
49
 * sub-classes to deviate from the default. Unwraps the content of a
50 51 52
 * {@link PayloadApplicationEvent} if necessary to allow method declaration
 * to define any arbitrary event type. If a condition is defined, it is
 * evaluated prior to invoking the underlying method.
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
 *
 * @author Stephane Nicoll
 * @since 4.2
 */
public class ApplicationListenerMethodAdapter implements GenericApplicationListener {

	protected final Log logger = LogFactory.getLog(getClass());

	private final String beanName;

	private final Method method;

	private final Class<?> targetClass;

	private final Method bridgedMethod;

	private final ResolvableType declaredEventType;

	private final AnnotatedElementKey methodKey;

	private ApplicationContext applicationContext;

	private EventExpressionEvaluator evaluator;

77 78
	private String condition;

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
	public ApplicationListenerMethodAdapter(String beanName, Class<?> targetClass, Method method) {
		this.beanName = beanName;
		this.method = method;
		this.targetClass = targetClass;
		this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
		this.declaredEventType = resolveDeclaredEventType();
		this.methodKey = new AnnotatedElementKey(this.method, this.targetClass);
	}

	/**
	 * Initialize this instance.
	 */
	void init(ApplicationContext applicationContext, EventExpressionEvaluator evaluator) {
		this.applicationContext = applicationContext;
		this.evaluator = evaluator;
	}

	@Override
	public void onApplicationEvent(ApplicationEvent event) {
98 99 100 101 102 103 104 105
		processEvent(event);
	}

	/**
	 * Process the specified {@link ApplicationEvent}, checking if the condition
	 * match and handling non-null result, if any.
	 */
	public void processEvent(ApplicationEvent event) {
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
		Object[] args = resolveArguments(event);
		if (shouldHandle(event, args)) {
			Object result = doInvoke(args);
			if (result != null) {
				handleResult(result);
			}
			else {
				logger.trace("No result object given - no result to handle");
			}
		}
	}

	/**
	 * Resolve the method arguments to use for the specified {@link ApplicationEvent}.
	 * <p>These arguments will be used to invoke the method handled by this instance. Can
	 * return {@code null} to indicate that no suitable arguments could be resolved and
	 * therefore the method should not be invoked at all for the specified event.
	 */
	protected Object[] resolveArguments(ApplicationEvent event) {
		if (!ApplicationEvent.class.isAssignableFrom(this.declaredEventType.getRawClass())
				&& event instanceof PayloadApplicationEvent) {
			Object payload = ((PayloadApplicationEvent) event).getPayload();
			if (this.declaredEventType.isAssignableFrom(ResolvableType.forClass(payload.getClass()))) {
				return new Object[] {payload};
			}
		}
		else {
			return new Object[] {event};
		}
		return null;
	}

	protected void handleResult(Object result) {
		Assert.notNull(this.applicationContext, "ApplicationContext must no be null.");
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
		if (result.getClass().isArray()) {
			Object[] events = ObjectUtils.toObjectArray(result);
			for (Object event : events) {
				publishEvent(event);
			}
		}
		else if (result instanceof Collection<?>) {
			Collection<?> events = (Collection<?>) result;
			for (Object event : events) {
				publishEvent(event);
			}
		}
		else {
			publishEvent(result);
		}
	}

	private void publishEvent(Object event) {
		if (event != null) {
			this.applicationContext.publishEvent(event);
		}
161 162 163 164 165 166 167
	}


	private boolean shouldHandle(ApplicationEvent event, Object[] args) {
		if (args == null) {
			return false;
		}
168
		String condition = getCondition();
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
		if (StringUtils.hasText(condition)) {
			Assert.notNull(this.evaluator, "Evaluator must no be null.");
			EvaluationContext evaluationContext = this.evaluator.createEvaluationContext(event,
					this.targetClass, this.method, args);
			return this.evaluator.condition(condition, this.methodKey, evaluationContext);
		}
		return true;
	}

	@Override
	public boolean supportsEventType(ResolvableType eventType) {
		if (this.declaredEventType.isAssignableFrom(eventType)) {
			return true;
		}
		else if (PayloadApplicationEvent.class.isAssignableFrom(eventType.getRawClass())) {
			ResolvableType payloadType = eventType.as(PayloadApplicationEvent.class).getGeneric();
			return eventType.hasUnresolvableGenerics() || this.declaredEventType.isAssignableFrom(payloadType);
		}
		return false;
	}

	@Override
	public boolean supportsSourceType(Class<?> sourceType) {
		return true;
	}

	@Override
	public int getOrder() {
197
		Order order = getMethodAnnotation(Order.class);
198 199 200
		return (order != null ? order.value() : 0);
	}

201 202 203 204
	protected <A extends Annotation> A getMethodAnnotation(Class<A> annotationType) {
		return AnnotationUtils.findAnnotation(this.method, annotationType);
	}

205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
	/**
	 * Invoke the event listener method with the given argument values.
	 */
	protected Object doInvoke(Object... args) {
		Object bean = getTargetBean();
		ReflectionUtils.makeAccessible(this.bridgedMethod);
		try {
			return this.bridgedMethod.invoke(bean, args);
		}
		catch (IllegalArgumentException ex) {
			assertTargetBean(this.bridgedMethod, bean, args);
			throw new IllegalStateException(getInvocationErrorMessage(bean, ex.getMessage(), args), ex);
		}
		catch (IllegalAccessException ex) {
			throw new IllegalStateException(getInvocationErrorMessage(bean, ex.getMessage(), args), ex);
		}
		catch (InvocationTargetException ex) {
			// Throw underlying exception
			Throwable targetException = ex.getTargetException();
			if (targetException instanceof RuntimeException) {
				throw (RuntimeException) targetException;
			}
			else {
				String msg = getInvocationErrorMessage(bean, "Failed to invoke event listener method", args);
				throw new UndeclaredThrowableException(targetException, msg);
			}
		}
	}

	/**
	 * Return the target bean instance to use.
	 */
	protected Object getTargetBean() {
		Assert.notNull(this.applicationContext, "ApplicationContext must no be null.");
		return this.applicationContext.getBean(this.beanName);
	}

242 243
	/**
	 * Return the condition to use. Matches the {@code condition} attribute of the
244 245
	 * {@link EventListener} annotation or any matching attribute on a composed
	 * annotation.
246 247 248
	 */
	protected String getCondition() {
		if (this.condition == null) {
249
			// TODO annotationAttributes are null with proxy
250 251 252 253 254 255
			AnnotationAttributes annotationAttributes = AnnotatedElementUtils
					.getAnnotationAttributes(this.method, EventListener.class.getName());
			if (annotationAttributes != null) {
				String value = annotationAttributes.getString("condition");
				this.condition = (value != null ? value : "");
			}
256 257
			// TODO Remove once AnnotatedElementUtils supports annotations on proxies
			else {
258
				EventListener eventListener = getMethodAnnotation(EventListener.class);
259
				this.condition = (eventListener != null ? eventListener.condition() : "");
260 261 262 263 264
			}
		}
		return this.condition;
	}

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 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
	/**
	 * Add additional details such as the bean type and method signature to
	 * the given error message.
	 * @param message error message to append the HandlerMethod details to
	 */
	protected String getDetailedErrorMessage(Object bean, String message) {
		StringBuilder sb = new StringBuilder(message).append("\n");
		sb.append("HandlerMethod details: \n");
		sb.append("Bean [").append(bean.getClass().getName()).append("]\n");
		sb.append("Method [").append(this.bridgedMethod.toGenericString()).append("]\n");
		return sb.toString();
	}

	/**
	 * Assert that the target bean class is an instance of the class where the given
	 * method is declared. In some cases the actual bean instance at event-
	 * processing time may be a JDK dynamic proxy (lazy initialization, prototype
	 * beans, and others). Event listener beans that require proxying should prefer
	 * class-based proxy mechanisms.
	 */
	private void assertTargetBean(Method method, Object targetBean, Object[] args) {
		Class<?> methodDeclaringClass = method.getDeclaringClass();
		Class<?> targetBeanClass = targetBean.getClass();
		if (!methodDeclaringClass.isAssignableFrom(targetBeanClass)) {
			String msg = "The event listener method class '" + methodDeclaringClass.getName() +
					"' is not an instance of the actual bean instance '" +
					targetBeanClass.getName() + "'. If the bean requires proxying " +
					"(e.g. due to @Transactional), please use class-based proxying.";
			throw new IllegalStateException(getInvocationErrorMessage(targetBean, msg, args));
		}
	}

	private String getInvocationErrorMessage(Object bean, String message, Object[] resolvedArgs) {
		StringBuilder sb = new StringBuilder(getDetailedErrorMessage(bean, message));
		sb.append("Resolved arguments: \n");
		for (int i = 0; i < resolvedArgs.length; i++) {
			sb.append("[").append(i).append("] ");
			if (resolvedArgs[i] == null) {
				sb.append("[null] \n");
			}
			else {
				sb.append("[type=").append(resolvedArgs[i].getClass().getName()).append("] ");
				sb.append("[value=").append(resolvedArgs[i]).append("]\n");
			}
		}
		return sb.toString();
	}


	private ResolvableType resolveDeclaredEventType() {
S
Stephane Nicoll 已提交
315 316
		int count = this.method.getParameterTypes().length;
		if (count != 1) {
317 318 319 320 321 322 323 324 325 326 327 328
			throw new IllegalStateException("Only one parameter is allowed " +
					"for event listener method: " + method);
		}
		return ResolvableType.forMethodParameter(this.method, 0);
	}

	@Override
	public String toString() {
		return this.method.toGenericString();
	}

}