springAOP是面向切面编程,它一共有6个概念
①JoinPoint(连接点)所谓连接点是指那些被拦截到的点,在spring中这些点指的是方法,因为spring只支持方法类型的连接点
②PointOut(切入点)所谓切入点是指我们要对哪些JoinPoint进行拦截的定义
③Advice通知/增强,拦截到JoinPoint之后所做的事情就是通知,通知的类型有前置通知,后置通知,异常通知,环绕通知,最终通知
④Introduction引界是一种特殊的通知,在不改变类的前提下,Introduction可以在运行期为类动态的添加一些方法
⑤Target(目标对象)植入Advice的目标对象
再通过代码实验一下
新建一个Account接口及其实现类
public interface Account {
public void save();
}
public class AccountImpl implements Account {
public void save(){
System.out.println("省了100元");
}
}
然后再新建一个拦截类
public class Aspect {
public void before(){
System.out.println("前置通知");
}
public void afterReturn(){
System.out.println("后置通知");
}
public void afterThrow(){
System.out.println("异常通知");
}
public void after(){
System.out.println("最终通知");
}
}
最后配置xml文件
<bean id="Account" class="Test4.AccountImpl"></bean>
<bean id="Aspect" class="Test4.Aspect"></bean>
<aop:config>
<aop:aspect id="ascpect" ref="Aspect">
<aop:before method="before" pointcut="execution(public void Test4..AccountImpl.save())"></aop:before>
<aop:after-returning method="afterReturn" pointcut="execution(public void Test4..AccountImpl.save())"></aop:after-returning>
<aop:after-throwing method="afterThrow" pointcut="execution(public void Test4..AccountImpl.save())"></aop:after-throwing>
<aop:after method="after" pointcut="execution(public void Test4..AccountImpl.save())"></aop:after>
</aop:aspect>
</aop:config>
最后测试得到结果
public class Test {
public static void main(String[]args){
ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
Account account=(Account)context.getBean("Account");
account.save();
}
}
/*前置通知
省了100元
后置通知
最终通知*/
除此之外AOP还有环绕通知,我们也可以通过方法来配置通知,就是调用ProceedingJoinPoint接口即可
public class Around {
public void around(ProceedingJoinPoint pjp){
try{
System.out.println("前置通知");
pjp.proceed();
System.out.println("后置通知");
}catch (Throwable e){
System.out.println("异常通知");
}
finally {
System.out.println("最终通知");
}
}
}
结果和上面一样,还有就是异常通知和后置通知是不能一起出现的