SpringAOP————基于schema的实现

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框架找不到自己想要的方法,所以报出了上述错误. 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值