• 参考Shiro的自定义基于Spring的AOP横切模式


    概要

    创建一个切入点PointcutAdvisor继承Spring的StaticMethodMatcherPointcutAdvisor

    创建一个MethodInterceptor方法拦截器org.aopalliance.intercept.MethodInvocation

    setAdvice(MethodInvocation mi)设置通知时传入一个MethodInterceptor方法拦截器

    调用Demo

    package com.wjz.demo;
    
    import org.springframework.aop.framework.ProxyFactory;
    
    import com.wjz.spring.CustomPointcutAdvisor;
    
    public class AopDemo {
    
        public static void main(String[] args) {
            ProxyFactory proxyFactory = new ProxyFactory();
            proxyFactory.addAdvisors(new CustomPointcutAdvisor());
            proxyFactory.setTarget(new Foo());
            Foo fooProxy = (Foo) proxyFactory.getProxy();
            fooProxy.foo("wjz");
        }
    }

    PointcutAdvisor切入点

    package com.wjz.spring;
    
    import java.lang.reflect.Method;
    
    import org.springframework.aop.support.StaticMethodMatcherPointcutAdvisor;
    
    /**
     * 自定义方法切入点
     * @author wjz
     *
     */
    @SuppressWarnings("serial")
    public class CustomPointcutAdvisor extends StaticMethodMatcherPointcutAdvisor {
    
        public CustomPointcutAdvisor() {
            setAdvice(new CustomMethodInterceptor());
        }
        
        @Override
        public boolean matches(Method method, Class<?> targetClass) {
            if ("foo".equals(method.getName())) {
                return true;
            }
            return false;
        }
    
    }

    MethodInterceptor方法拦截器

    package com.wjz.spring;
    
    import java.lang.reflect.Method;
    
    import org.aopalliance.intercept.MethodInterceptor;
    import org.aopalliance.intercept.MethodInvocation;
    
    /**
     * 自定义方法拦截器
     * @author wjz
     *
     */
    public class CustomMethodInterceptor implements MethodInterceptor {
    
        @Override
        public Object invoke(MethodInvocation invocation) throws Throwable {
            System.out.println("invoke method before");
            
            Object arg = invocation.getArguments()[0];
            System.out.println("arg " + arg);
            
            Object ti = invocation.getThis();
            System.out.println("this " + ti);
            
            Method method = invocation.getMethod();
            System.out.println("method " + method);
            
            System.out.println("toString " + toString());
            
            Object result = invocation.proceed();
            System.out.println("invoke method after");
            return result;
        }
    
    }
  • 相关阅读:
    第五章:向量运算
    第四章:向量
    第三章:多坐标系
    近期一些学习的随笔
    2020高考游记
    寒假集训好题记录
    STL基本用法的一些记录
    2020暑假集训做题记录——数据结构
    2020.12.13~2020.12.20做题记录
    2020.11.30~2020.12.6 做题记录
  • 原文地址:https://www.cnblogs.com/BINGJJFLY/p/9065798.html
Copyright © 2020-2023  润新知