spring 3.2.4
为了给每一个controller配置一个拦截器链
import com.google.common.collect.Lists; import org.aopalliance.intercept.MethodInterceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.aop.TargetSource; import org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import java.util.List; @Component public class AutoProxyCreator extends AbstractAutoProxyCreator implements InitializingBean { /** * 序列化版本号 */ private static final long serialVersionUID = 1L; /** * 持有Spring应用上下文 */ private volatile ApplicationContext context = null; /** * 日志打印 */ private static Logger logger = LoggerFactory.getLogger(AutoProxyCreator.class); /** * 拦截器链 */ private List<String> intercaptorChainList = null; /** * 实现自动代理 */ @Override protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, TargetSource targetSource) { // 针对Controller和RequestMapping进行拦截 if (AnnotationUtils.findAnnotation(beanClass, Controller.class) != null || AnnotationUtils.findAnnotation(beanClass, RequestMapping.class) != null) { if (intercaptorChainList == null) { throw new RuntimeException("初始化拦截器链失败,异常中断程序!"); } List<MethodInterceptor> methodInterceptorList = Lists.newArrayList(); for(String intercaptor : intercaptorChainList){ if(AnnotationUtils.findAnnotation(beanClass, ExceptedAuthValidate.class) != null ){ continue; } logger.info("开始为bean:"{}"配置拦截器链:"{}"", beanClass, intercaptor); BeanFactory beanFactory = getBeanFactory(); MethodInterceptor methodInterceptor = (MethodInterceptor)beanFactory.getBean(intercaptor); methodInterceptorList.add(methodInterceptor); } return methodInterceptorList.toArray(); } return DO_NOT_PROXY; } /** * 初始化拦截器链 */ @Override public void afterPropertiesSet() throws Exception { intercaptorChainList = Lists.newArrayList(); intercaptorChainList.add("userLoginInterceptor"); intercaptorChainList.add("paramValidateInterceptor"); } }
然后跑起来发现所有的controller都访问不了了
AbstractHandlerMethodMapping里打断点可以看到
被代理了之后,getType出来是代理类,代理类没有注解
被认为不是一个handler
但是普通的AOP却没有问题,还需要了解AOP和这种代理有什么区别