package com.usoftchina.uas.office.listener;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * @author yingp
 * @date 2020/2/16
 */
@Component
public class UasEventListenerProcessor implements BeanPostProcessor {
    @Autowired
    private UasEventListenerFactory eventListenerFactory;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Method[] methods = ReflectionUtils.getAllDeclaredMethods(bean.getClass());
        if (methods != null) {
            for (Method method : methods) {
                if (method.isAnnotationPresent(UasEventListener.class)) {
                    UasEventListener listener = method.getAnnotation(UasEventListener.class);
                    eventListenerFactory.addListener(listener, bean, method);
                }
            }
        }
        return bean;
    }
}
