• spring-AOP-基于@AspectJ切面的小例子


    条件:

    1.jdk的版本在5.0或者以上,否则无法使用注解技术

    2.jar包:

      aspectjweaver-1.7.4.jar

      aspectjrt-1.7.4.jar

      spring-framework-bom-4.0.5.RELEASE-sources.jar

    开始编写一个简单的基于@AspectJ的切面

    //代理对象
    public class testweaver {
        public void hello(){
            System.out.println("hello,world");
        }
    }
    @Aspect //通过注解的方式标示为切面
    public class TestAnnotationAspect {//定义切点@Before和增强类型
        @Before("execution(* hello(..)))")
        public void doBefore(){
            System.out.println("前置通知");
        }
        //定义切点@After和增强类型
        @After("execution(* hello(..)))")
        public void doAfter(){
             System.out.println("最终通知"); 
        }
    }
    public class Test{
       public static void main(String[] args) {
                  //创建对象
            AspectJProxyFactory a = new AspectJProxyFactory();
            testweaver t = new testweaver();
                  //设置目标对象
            a.setTarget(t);
                  //设置切面类
            a.addAspect(TestAnnotationAspect.class);
                  //生成织入的代理对象
            testweaver t2 = a.getProxy();                                                  
            t2.hello();
        }
    }

     整个流程:

    在这个例子中, testweaver类和TestAnnotationAspect类都只是一个简单的类,而TestAnnotationAspect类标注了@AspectJ的注解,

    这让在后续的第三方程序能检测的到拥有@Aspect的类是否是一个切面类。

    其次,TestAnnotationAspect类中的doBefore() 标注了@Before,意思为前置增强。后面的execution() 使用切点函数的方法匹配模式串注明了成员值。

    而成员值为一个@Aspectj切点表达式,意思为在目标类的hello()上织入增强,可以带入任意的入参和任意的返回值。

    最后通过org.springframework.aop.aspectj.annotation.AspectJProxyFactory 为 testweaver类生成切面代理。

  • 相关阅读:
    mysql 5.7开启sql日志的配置
    Apache显示目录列表及icons目录的问题
    WebGL学习笔记二——绘制基本图元
    java上传文件类型检测
    binlog
    vs2015下C4819该文件包含不能在当前代码页(936)中表示的字符问题解决
    WebGL学习笔记一
    vs2015 debug时出现 C2039“cout”: 不是“std”的成员
    spring boot实现切割分片上传
    springboot自定义类@Resource注入为null的问题
  • 原文地址:https://www.cnblogs.com/tjc1996/p/5720411.html
Copyright © 2020-2023  润新知