springAOP面向切面的简单应用
需要两个类,一个类作为切入点,一个类作为切面类。
两种方法:编写XML配置文件和使用注解
1.使用编写XML文件的方式:
切入点类
public class Test {
public void ts() {
System.out.println("一个普通方法");
throw new NullPointerException();
}
}
切面类
public class AopQ {
public void beFore(){
System.out.println("前置通知");
}
public void after(){
System.out.println("后置通知");
}
public void returning(Object ar){
System.out.println("返回后通知"+ar.toString());
}
public void thorwing(NullPointerException e){
System.out.println("抛出异常后通知"+e.toString());
}
}
配置文件
<aop:config>
<aop:aspect id="asp" ref="aq"><!-- bean id为aq的类作为切面类 -->
<aop:pointcut expression="excution(* com.anzhuo.jiangyiling.Test.*(..))" id="poi"/><!-- 规定切入点,切入规则 -->
<aop:before pointcut-ref="poi" method="beFore"/>
<aop:after pointcut-ref="poi" method="after"/>
<aop:after-returning pointcut-ref="poi" method="retruning" returning="ar"/>
<aop:after-throwing pointcut-ref="poi" method="throwing" throwing="e"/>
</aop:aspect>
</aop:config>
2.使用注解的方式:
在切面类中
@Aspect//此类作为切面类
public class AopQ {
@Pointcut("execution(* com.anzhuo.jiangyiling.*.*(..))")//规定切入点,切入规则
public void qr(){}
@Before("qr()")
public void beforeA(){
System.out.println("前置");
}
@AfterReturning(pointcut="qr()",returning="s")
public void afterR(String s){
System.out.println("返回后通知");
}
@AfterThrowing(pointcut="qr()",throwing="o")
public void afterT(Object o){
System.out.println("抛出异常后通知");
}
}
配置文件中只需加上<aop:aspectj-autoproxy/>