【Spring-AOP】基于注解的AOP配置
6 基于注解的AOP配置
6.1 XML配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--需要被代理的类-->
<bean id="Man" class="com.moon.point.Man"/>
<!--开启组件扫描-->
<context:component-scan base-package="com.moon"/>
<!--开启aop注解模式-->
<aop:aspectj-autoproxy/>
</beans>
6.2 前后置通知
使用java类来配置一个切面
// 加入组件,交给ioc管理
@Component
// 声明是一个切面类
@Aspect
public class AnnotationAspect {
/**
* 配置切入点
*/
@Pointcut("execution(* com.moon.point.Man.*(..))")
private void pointCut(){}
/**
* 前置通知,将前面配置的切入点引入
*/
@Before("pointCut()")
public void beforeAdvice(){
System.out.println("This is beforeAdvice!");
}
/**
* 后置通知,将前面配置的切入点引入
*/
@After("pointCut()")
public void afterAdvice(){
System.out.println("This is afterAdvice!");
}
/**
* 后置返回通知,可以指定返回的参数的接收值
* @param result 返回参数接收
*/
@AfterReturning(value = "pointCut()",returning = "result")
public void afterReturning(Object result){
System.out.println("This is afterReturning! Result is "+result);
}
/**
* 后置异常通知,可以指定异常参数的接收
* @param e 异常接收
*/
@AfterThrowing(value = "pointCut()",throwing = "e")
public void afterThrowing(Exception e){
System.out.println("This is afterReturning! Exception is "+e.getMessage());
}
}
结果:
6.3 环绕通知
// 加入组件,交给ioc管理
@Component
// 声明是一个切面类
@Aspect
public class AnnotationAspect {
/**
* 配置切入点
*/
@Pointcut("execution(* com.moon.point.Man.*(..))")
private void pointCut(){}
/**
* 环绕通知配置,引入切点
* @param point 连接点
* @return 执行后返回值
* @throws Throwable 方法执行异常
*/
@Around("pointCut()")
@Around("pointCut()")
public Object aroundAdvice(ProceedingJoinPoint point) throws Throwable {
try {
// 前置通知
System.out.println("This is around-beforeAdvice");
// 执行方法,拿到返回值
Object proceed = point.proceed();
// 后置返回值方法
System.out.println("This is around-afterReturningAdvice! result is " + proceed);
return proceed;
} catch (Throwable e) {
// 后置异常方法
System.out.println("This is around-afterThrowingAdvice! Exception Message is " + e.getMessage());
throw e;
} finally {
// 后置finally方法
System.out.println("This is around-afterFinallyAdvice!");
}
}
}
结果: