tnt.common.monitoring.GuardedByAnnotationBeanPostProcessor.java Source code

Java tutorial

Introduction

Here is the source code for tnt.common.monitoring.GuardedByAnnotationBeanPostProcessor.java

Source

// 2003-2013 Adobe Systems Inc. All Rights Reserved.
//This software is proprietary; use is subject to license terms.
package tnt.common.monitoring;

import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.MethodCallback;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Component
public class GuardedByAnnotationBeanPostProcessor implements BeanPostProcessor {

    public GuardedByAnnotationBeanPostProcessor() {
    }

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

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        final List<Method> guardedMethods = new ArrayList<>();
        ReflectionUtils.doWithMethods(bean.getClass(), new MethodCallback() {
            @Override
            public void doWith(Method method) {
                if (method.isAnnotationPresent(GuardedBy.class)) {
                    guardedMethods.add(method);
                }
            }
        });
        return guardedMethods.isEmpty() ? bean : createProxy(bean, guardedMethods);
    }

    protected Object createProxy(Object target, List<Method> methods) {
        ProxyFactory proxyFactory = new ProxyFactory(target);
        proxyFactory.addAdvice(new HystrixInterceptor());
        return proxyFactory.getProxy();
    }

}