1 /* 2 * Copyright 2002-2009 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.context.event; 18 19 import org.springframework.aop.support.AopUtils; 20 import org.springframework.context.ApplicationEvent; 21 import org.springframework.context.ApplicationListener; 22 import org.springframework.core.GenericTypeResolver; 23 import org.springframework.core.Ordered; 24 import org.springframework.util.Assert; 25 26 /** 27 * {@link SmartApplicationListener} adapter that determines supported event types 28 * through introspecting the generically declared type of the target listener. 29 * 30 * @author Juergen Hoeller 31 * @since 3.0 32 * @see org.springframework.context.ApplicationListener#onApplicationEvent 33 */ 34 public class GenericApplicationListenerAdapter implements SmartApplicationListener { 35 36 private final ApplicationListener delegate; 37 38 39 /** 40 * Create a new GenericApplicationListener for the given delegate. 41 * @param delegate the delegate listener to be invoked 42 */ GenericApplicationListenerAdapter(ApplicationListener delegate)43 public GenericApplicationListenerAdapter(ApplicationListener delegate) { 44 Assert.notNull(delegate, "Delegate listener must not be null"); 45 this.delegate = delegate; 46 } 47 48 49 @SuppressWarnings("unchecked") onApplicationEvent(ApplicationEvent event)50 public void onApplicationEvent(ApplicationEvent event) { 51 this.delegate.onApplicationEvent(event); 52 } 53 supportsEventType(Class<? extends ApplicationEvent> eventType)54 public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) { 55 Class typeArg = GenericTypeResolver.resolveTypeArgument(this.delegate.getClass(), ApplicationListener.class); 56 if (typeArg == null || typeArg.equals(ApplicationEvent.class)) { 57 Class targetClass = AopUtils.getTargetClass(this.delegate); 58 if (targetClass != this.delegate.getClass()) { 59 typeArg = GenericTypeResolver.resolveTypeArgument(targetClass, ApplicationListener.class); 60 } 61 } 62 return (typeArg == null || typeArg.isAssignableFrom(eventType)); 63 } 64 supportsSourceType(Class<?> sourceType)65 public boolean supportsSourceType(Class<?> sourceType) { 66 return true; 67 } 68 getOrder()69 public int getOrder() { 70 return (this.delegate instanceof Ordered ? ((Ordered) this.delegate).getOrder() : Ordered.LOWEST_PRECEDENCE); 71 } 72 73 } 74