Spring AOP的方式主要有两种:一种是通过xml文件的方式,第二种是通过注解的方式。
通过xml文件
首先,编写相应的切面代码

其次编写相应的xml文件

先在配置文件上给刚刚的日志类在配置文件上声明相应的bean,然后再进行相应的aop的定义。要确定一个切面,只需要确定该切面在什么时候(<aop:pointcut>)利用哪个类中(<aop:aspect ref="...">)的什么方法(aop:before/after/after-returning/after-throwing/around)。需要aop发挥作用,还需要在xml配置文件中添加代理:<aop:aspectj-autoproxy/>和在头部添加相应的命名空间

编写相应的测试程序可以看到如下结果:


可以看到在运行getName()方法前,会先运行我们定义的切面函数,在getName()方法运行后,也会运行相应的切面函数,可是我们并不需要在核心业务的代码上添加相应的方法,只需要定义好切面,系统将会为我们在恰当的时间点做相应的事情。
通知函数
<aop:before/after...>等标签定义的是通知函数,通知函数就是在切点触发时所运行的方法,而运行的时间点有5种:before, after, after-returning, after-throwing, around。

这五个时间点具体意义如下:

表达式
定义切面的切入点(pointcut)主要是通过表达式来进行定义

上述的表达式定义的切点是在edu.stu.pojo.Student类里面的任意方法。而这种表达式主要是通过切入点指示符来进行描述,切入点指示符主要有:within(<type name>)根据类名来进行过滤,execution(<scope> <return-type> <fully-qualified-class-name>.*(parameters))根据方法进行过滤,还有一些其他的表达式,这里就不列出。还有一些辅助使用的通配符:..(用在方法中指任意数量的参数,用在包中指任意数量的包),+(代表任意子类),*(代表任意字符)。
利用@Aspect注解
利用@Aspect注解来标识切面函数,其实和用注解标记pojo类一样,我们不需要在配置文件中再写类似于上述的<aop>标签,而只是通过一些注解来完成配置文件的描述那样,下面是通过@Aspect注解定义的一个类。
@Aspect
注解,相当于在xml文件中定义一个切面,通常@Aspect注解是对类来进行标识;

@Pointcut注解就是用来定义切点,这个注解就相当于在xml文件上编写<aop:pointcut>标签,其中注解内的属性就是定义的表达式,而函数名(selectAll())就是该切点的名字。然后通过后面的@Before, @After等通知函数标签来标识通知函数。同样,也可以直接在通知函数标签里定义表达式,来免除@Pointcut的注解
感想
通过Spring AOP的技术,可以让我们的代码更为集中于我们的核心业务,可以将与其关系不大的代码提取出来,并且在适当的时候动态织入。可是由于本人对Spring框架初学,在运用方面较少,所以还未感受到Spring AOP更大的好处,或者在项目运用上还没有较好地实践。
网友评论