在Spring 实现通过XML文件配置使用面向切面编程AOP
PART :XML配置文件中实现springAOP
一:首先要写好对应的类和切面类
//Calculator
public class CalculatorImp implements Calculator {
@Override
public int add(int a, int b) {
return a+b;
}
@Override
public int sub(int a, int b) {
return 0;
}
@Override
public int mul(int a, int b) {
return 0;
}
@Override
public int div(int a, int b) {
return a%b;
}
}
//切面类
public class LoggingAspect {
//前置通知
public void BeforeMethod(JoinPoint joinPoint){
//获得方法的名称
String methodName = joinPoint.getSignature().getName();
System.out.println("Method name : "+methodName);
//获得参数
Object[] args = joinPoint.getArgs();
System.out.println("args : "+ Arrays.asList(args));
}
//后置通知,在方法执行结束之后(无论是否发生异常),进行通知。这个通知一定会执行
//在后置通知中之无法访问目标方法的执行结果(如果方法执行过程中发生异常,是没有返回结果的),执行结果在返回通知中可以访问
public void after(JoinPoint joinPoint){
System.out.println("MethodName : "+joinPoint.getSignature().getName()+" ends");
}
//返回通知
public void afterReturning(JoinPoint joinPoint,Object result){
System.out.println("the returning is :"+result);
}
/**
* 异常通知:目标方法出现异常,并且出现的异常和通知参数的异常类型一致的时候才会执行这个通知
* @param joinPoint
* @param ex
*/
public void afterThrowingException(JoinPoint joinPoint,Exception ex){
}
/** 全面,但是不常用
* 环绕通知需要携带ProceedingJoinPoint 类型的参数
* 环绕通知类似于动态代理:ProceedingJoinPoint 类型的参数可以据欸的那个是否执行目标方法;也可以获取链接细节(类似JoinPoint)
* 环绕通知必须有返回值,及返回值就是目标方法的返回值
* @param pdj
* @return
*/
public Object around(ProceedingJoinPoint pdj) {
Object result = null;
try {
//前置通知
String methodName = pdj.getSignature().getName();
pdj.proceed();
//返回通知
} catch (Throwable throwable) {
throwable.printStackTrace();
//异常通知
}
//后置通知
return result;
}
}
二:在XML 文件中进行配置
//1. 配置bean
<!--配置bean-->
<bean id="Calculator" class="AOP.AOP_second.CalculatorImp"></bean>
//2. 配置切面类的bean
<!--配置切面类的Bean-->
<bean id="LoggingAspect" class="AOP.AOP_second.LoggingAspect"></bean>
//3. 配置AOP
*主要是配置切点,切面,通知方法
<aop:config>
<!--配置切点表达式-->
<aop:pointcut expression="execution(public int blogwebsite.A_Spring_Test.Calculator.div(int,int))" id="pointcut"/>
<!--配置切面和通知-->
<aop:aspect ref="LoggingAspect" order="2">
<!--前置通知-->
<aop:before menthod="BeforeMethod" pointcut-ref="pointcut">
<!--后置通知-->
<aop:after menthod="AfterMethod" pointcut-ref="pointcut">
<!--异常通知-->
<aop:after-throwing menthod="afterThrowingException" pointcut-ref="pointcut">
<!--返回通知-->
<aop:after-returning menthod="afterReturning" pointcut-ref="pointcut">
<!--环绕通知-->
<aop:around menthod="around" pointcut-ref="pointcut">
</aop:aspect>