美文网首页
5.4.4spring aop创建通知

5.4.4spring aop创建通知

作者: 仙境源地 | 来源:发表于2019-11-05 15:23 被阅读0次

    spring支持六种通知


    aop通知1
    aop通知2

    5.4.5通知接口

    Advice接口
    Advice(通知) VS Advisor(顾问)

    Advice(通知)

    功能简单,只能将切面织入到目标类的所有目标方法

    Advisor(顾问)

    更为复杂的切面织入功能,可以指定具体的切入点,从而可以更细致地控制在哪个连接点上拦截通知.

    PointcutAdvisor是顾问的一种

    TODO:cj

    image.png

    5.4.6创建前置通知(Before advice)

    用途
    1.可以修改传递给方法的参数。
    2.可以通过抛出异常来阻止方法的执行。

    源码chapter05/simple-before-advice

    package com.apress.prospring5.ch5;
    
    import com.apress.prospring5.ch2.common.Singer;
    
    /**
     * Created by iuliana.cosmina on 3/26/17.
     */
    public class Guitarist implements Singer {
    
        private String lyric = "You're gonna live forever in me";
    
        @Override
        public void sing() {
            System.out.println(lyric);
        }
    
        public void song() {
            System.out.println("song:" + lyric);
        }
    }
    
    package com.apress.prospring5.ch5;
    
    import org.springframework.aop.MethodBeforeAdvice;
    import org.springframework.aop.framework.ProxyFactory;
    
    import java.lang.reflect.Method;
    
    public class SimpleBeforeAdvice implements MethodBeforeAdvice {
        public static void main(String... args) {
            Guitarist johnMayer = new Guitarist();
    
            ProxyFactory pf = new ProxyFactory();
            pf.addAdvice(new SimpleBeforeAdvice());
            pf.setTarget(johnMayer);
    
            Guitarist proxy = (Guitarist) pf.getProxy();
    
            proxy.sing();
            proxy.song();
        }
    
        @Override
        public void before(Method method, Object[] args, Object target)
                throws Throwable {
            System.out.println("Before '" + method.getName() + "', tune guitar.");
        }
    }
    

    执行结果

    Before 'sing', tune guitar.
    You're gonna live forever in me
    Before 'song', tune guitar.
    song:You're gonna live forever in me
    

    5.4.7通过使用前置通知阻止方法访问

    相关文章

      网友评论

          本文标题:5.4.4spring aop创建通知

          本文链接:https://www.haomeiwen.com/subject/vnidbctx.html