spring 切面配置

Spring AOP配置方式可以选择注解方式,或者xml配置

(一)注解方式

类名上面添加注解

@Order(数字) //(可选)数字表示切面的优先级,数字越小优先级越高

@Aspect  //(必选)

@Component  //(必选)

public class AOP {

/**
* 定义一个方法, 用于声明切入点表达式. 一般地, 该方法中再不需要添入其他的代码. 
* 使用 @Pointcut 来声明切入点表达式. 
* 后面的其他通知直接使用方法名来引用当前的切入点表达式. 
*/
@Pointcut("execution(public int testAOP.*.*(..)")
public void TestExecution(){}

/**
* 在 testAOP每一个实现类的每一个方法开始之前执行一段代码
*/
@Before("TestExecution()")
public void beforeMethod(){}
/**
* 在方法执行之后执行的代码. 无论该方法是否出现异常
*/
@After("TestExecution()")
public void afterMethod(JoinPoint joinPoint){}

/**
* 在方法法正常结束受执行的代码
* 返回通知是可以访问到方法的返回值的!
*/
@AfterReturning(value="TestExecution()",
returning="result")
public void afterReturning(){}

/**
* 在目标方法出现异常时会执行的代码.
* 可以访问到异常对象; 且可以指定在出现特定异常时在执行通知代码
*/
@AfterThrowing(value=""TestExecution()",
throwing="e")
public void afterThrowing(JoinPoint joinPoint, Exception e){}

/**
* 环绕通知需要携带 ProceedingJoinPoint 类型的参数. 
* 环绕通知类似于动态代理的全过程: ProceedingJoinPoint 类型的参数可以决定是否执行目标方法.
* 且环绕通知必须有返回值, 返回值即为目标方法的返回值
*/
/*
@Around("TestExecution()")
public Object aroundMethod(ProceedingJoinPoint pjd){

Object result = null;
String methodName = pjd.getSignature().getName();

try {
//前置通知
System.out.println(methodName + " begins with " + Arrays.asList(pjd.getArgs()));
//执行目标方法
result = pjd.proceed();
//返回通知
System.out.println(methodName + " ends with " + result);
} catch (Throwable e) {
//异常通知
System.out.println(methodName + " occurs exception:" + e);
throw new RuntimeException(e);
}
//后置通知
System.out.println(methodName);

return result;
}
*/


}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值