注解配置:
@Aspect
要建立一个Aspect类,必须要有@Aspect注解代表是一个切面类。
@Before 前置通知
@After 后置通知
@AfterReturning 返回通知
@AfterThrowing 异常通知
@Around 环绕通知
使得AspectJ注解起作用
<aop:aspect-autoproxy>
</aop:aspectj-autoproxy>
切面类变成要bean用 @Component
@Before("execution(public int com.iotek.cal.add(int,int))")
通配符
@Before("exexution(* com.iotek.cal.*(..))")
public void testBefore(JoinPoint joinPoint){
joinPoint.*
System.out.println("前置通知");
}
@AfterReturning(value="execution(*com.iotek.*(..))",returning="result")
public void testAfter(JoinPoint join,Object result){
System.out.println("返回通知","返回值:"+result);
}
@AfterThrowing(value="execution(*com.iotek.*(..))",throwing="e")
public void testAfterThrowing(JoinPoint joinpoint,Exception e){
System.out.println("异常通知:"e.getMessage());
}
@Around("execution(*com.iotek.*(..))")
public Object testAround(ProceedingJoinPoint pjp){
Object result=0;
System.out.println("前置通知");
try{
System.out.println("后置通知");
result = pjp.procedd();
System.out.println("返回通知");
}catch(Throwable throwable){
System.out.println("异常通知");
}
return result;
}
main{
ApplicationContext context=new ClassPathXmlApplicationContext(".xml");
接口 接口名=(接口类型) context.getBean("切面类");
}
@Order(1) 代表,两个代理的优先级,数字越小优先越高
xml配置:
<bean id="calculator" class="com.iotek.Caluculator"></bean>
<bean id="restAspect" class="com.iotek.切面的功能类"></bean>
<aop:config>
<aop:prointcut id="poi" expression=("execution(* com.iotek.Caluculator.*(..))")</aop:pointcut>
<asp:aspect ref="testAspect">
<aop:before method="切面类方法名" pointcut-ref="pointcut"></aop:before>
<aop:after-returning method="切面类方法名" pointcut-ref="pointcut" returning="切面类返回名"/>
<aop:after-throwing method="切面类方法名" pointcut-ref="pointcut" throwing="切面类异常名"/>
<aop:after method="切面类方法名" pointcut-ref="pointcut"></aop:after>
<aop:config>