美文网首页
使用注解(基于Aspect)

使用注解(基于Aspect)

作者: kanaSki | 来源:发表于2019-08-13 22:26 被阅读0次

    Spring不会自动寻找注解,必须告诉Spring哪些包中可能有注解
    在applicationContext.xml内配置如下即可:(需要引入xmlns:context)

        <context:component-scan base-package="com.Demo,com.advice"/>
        <!--true表示使用cglib动态代理,false表示使用jdk动态代理,注解都是使用cglib做的-->
        <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
    

    @Component注解相当于bean标签,id默认为类名首字母小写,也可以直接设置id

    package com;
    
    import org.aspectj.lang.annotation.Pointcut;
    import org.springframework.stereotype.Component;
    
    @Component("demo")
    public class Demo {
        @Pointcut("execution(* com.Demo.demo1())")
        public void demo1() {
            System.out.println("demo1");
        }
    
        public void demo2() throws Exception {
            int i = 1 / 0;
            System.out.println("demo2");
        }
    
        public void demo3() {
            System.out.println("demo3");
        }
    }
    

    通知类:

    package com.advice;
    
    import org.aspectj.lang.annotation.After;
    import org.aspectj.lang.annotation.Aspect;
    import org.springframework.stereotype.Component;
    
    @Component
    @Aspect
    public class AfterAdvice {
        @After("com.Demo.demo1()")
        public void after(){
            System.out.println("后置");
        }
    }
    

    相关文章

      网友评论

          本文标题:使用注解(基于Aspect)

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