zoukankan      html  css  js  c++  java
  • 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类生成切面代理。

  • 相关阅读:
    ISS6 WEB服务器不能访问 grf 报表模板文件的问题
    c# 读取记事本txt文档到DataTable中
    C# 泛型LIST转DataTable
    sql 查出一张表中重复的所有记录数据
    Coolite中GridPanel真实分页(储存过程方式)
    SQL对Xml字段的操作
    反射和特性 自定义转换datatable为强类型集合
    LINQ TO SQL 并发控制
    AS3 加载文件
    使ASP.NET网站Forms验证可以指定多个登录页面
  • 原文地址:https://www.cnblogs.com/tjc1996/p/5720411.html
Copyright © 2011-2022 走看看