1.导入相关jar包(具体看我的其它文章)
2.切点的实现(代码就不显示了)
3.通知类的实现
public class Advice {
public void before(JoinPoint p)
{
System.out.println("前置通知!");
}
public void after(JoinPoint p)
{
System.out.println("后置通知!");
}
public void exception(Throwable x)
{
System.out.println("异常通知!"+x.getMessage());
}
public void around(ProceedingJoinPoint p) throws Throwable
{
try {
System.out.println("环绕通知实现的前置通知!");
p.proceed();
System.out.println("环绕通知实现的后置通知!");
}
catch(Throwable e)
{
System.out.println("环绕通知实现的异常通知!"+e.getMessage());
}
}
4.配置xml
添加命名空间:
xmlns:aop="http://www.springframework.org/schema/aop"
把切点 通知类注入IOC容器,以及关联这两者
<bean id="student" class="org.aop.Object.Student"></bean>
<bean id="advice" class="org.aop.Advice.Advice"></bean> <!-- 将通知类注入IOC-->
<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(public void org.aop.Object.Student.display())" id="pointcut"/> <!-- 切点的声明定义-->
<aop:aspect ref="advice"> <!-- 关联通知类-->
<aop:before method="before" pointcut-ref="pointcut"/> <!-- 前置通知-->
<aop:after-returning method="after" pointcut-ref="pointcut" /><!-- 后置通知-->
<aop:after-throwing method="exception" pointcut-ref="pointcut" throwing="x"/><!-- 异常通知-->
<aop:around method="around" pointcut-ref="pointcut"/><!-- 环绕通知-->
</aop:aspect>
</aop:config>
注意:如果不能运行显示如下报错信息"java.lang.IllegalArgumentException: error at ::0 formal unbound in pointcut" 那么多半是你异常通知的参数直接使用却没有声明 或 后置通知的返回值参数直接使用却没有声明。
以异常通知为例:异常通知的方法是带有参数(Exception e),而在配置异常通知的时候,注解属性中没有声明这个参数e并且直接使用了,Spring框架在加载本类的时候,当加载异常通知的注解代码时,会去找无参的方法 ,但是实现异常通知的函数代码给出的却是有参的,Spring框架找不到自己想要的方法,所以报出了上述错误.