Spring的AOP也是常用功能功能之一使用该功能
使用AOP的功能仍然可以使用 注解与XML两种方式,这里我比较推荐xml方式配置,看着比较清晰,对于项目的配置文件,使用这种结构
将AOP的配置文件独立放置,然后使用一个xml文件引入;
1.使用xml配置AOP执行
<aop:config>
<aop:aspect id="audience" ref="audience">
<!--配置com.spring.service包下所有类或接口的所有方法 -->
<aop:pointcut id="performance"
expression="execution(* com.houlu.SpringDemo.AOPInstance.Performer.*(..))" />
<aop:before pointcut-ref="performance" method="takeSeats" />
<aop:before pointcut-ref="performance" method="turnOffCellPhones" />
<aop:after-returning pointcut-ref="performance"
method="applaud" />
<aop:after-throwing pointcut-ref="performance"
method="demandRefund" />
</aop:aspect>
</aop:config>
在这里配置好之后就可以对应在com.houlu.SpringDemo.AOPInstance.Performer.*(..)这个类的包下执行AOP相关操作了
2.使用注解配置AOP执行
AOP同样也支持注解的执行方式,这里必须要打开的标签是
<aop:aspectj-autoproxy/>
打开这段代码之后,AOP相关配置文件里面不许需写任何东西了,AOP的执行方法等内容可以直接配置到JAVA的代码段里,跟xml配制方法一样,此时定义在哪些包得哪些方法内部执行AOP相关操作;
package com.houlu.SpringDemo.AOPInstance;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
* 定义切面
* @author lu.hou
*
*/
@Component
@Aspect
public class Audience2 {
@Pointcut("execution(* com.houlu.SpringDemo.AOPInstance.Performer.*(..))")
public void anyMethod(){}
@Before("anyMethod()")
public void takeSeats(){
System.out.println("注解方式执行 : The audience is taking their seats.");
}
@After("anyMethod()")
public void turnOffCellPhones(){
System.out.println("注解方式执行 :The audience is turning off their cellphones");
}
public void applaud(){
System.out.println("注解方式执行 :CLAP CLAP CLAP");
}
public void demandRefund(){
System.out.println("注解方式执行 :Boo! We want money back");
}
}