001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.apache.shiro.spring; 020 021import org.apache.shiro.event.EventBus; 022import org.apache.shiro.event.EventBusAware; 023import org.apache.shiro.event.Subscribe; 024import org.apache.shiro.lang.util.ClassUtils; 025import org.apache.shiro.util.CollectionUtils; 026import org.springframework.beans.BeansException; 027import org.springframework.beans.factory.config.BeanPostProcessor; 028 029import java.util.List; 030 031/** 032 * Spring {@link BeanPostProcessor} that detects, {@link EventBusAware} and classes containing 033 * {@link Subscribe @Subscribe} methods. Any classes implementing EventBusAware will have the setEventBus() method 034 * called with the <code>eventBus</code>. Any classes discovered with methods that are annotated 035 * with @Subscribe will be automatically registered with the EventBus. 036 * 037 * <p><strong>NOTE:</strong> in a Spring environment implementing EventBusAware is not necessary, 038 * as you can just inject the EventBus with {@link org.springframework.beans.factory.annotation.Autowire @Autowire}.</p> 039 * 040 * @see EventBusAware 041 * @see Subscribe 042 * @since 1.4 043 */ 044public class ShiroEventBusBeanPostProcessor implements BeanPostProcessor { 045 046 private final EventBus eventBus; 047 048 public ShiroEventBusBeanPostProcessor(EventBus eventBus) { 049 this.eventBus = eventBus; 050 } 051 052 @Override 053 public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { 054 return bean; 055 } 056 057 @Override 058 public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { 059 if (bean instanceof EventBusAware) { 060 ((EventBusAware) bean).setEventBus(eventBus); 061 } else if (isEventSubscriber(bean)) { 062 eventBus.register(bean); 063 } 064 065 return bean; 066 } 067 068 private boolean isEventSubscriber(Object bean) { 069 List annotatedMethods = ClassUtils.getAnnotatedMethods(bean.getClass(), Subscribe.class); 070 return !CollectionUtils.isEmpty(annotatedMethods); 071 } 072 073}