SpringAOP———基于注解形式的实现

1.导入相关jar包

commons-logging-1.1.1.jar
spring-aop-4.3.9.RELEASE.jar
spring-beans-4.3.9.RELEASE.jar
spring-context-4.3.9.RELEASE.jar
spring-core-4.3.9.RELEASE.jar
spring-expression-4.3.9.RELEASE.jar
aopalliance-1.0.jar
aspectjweaver-1.5.3.jar

2.切点的实现以及注入IOC容器(实现代码就不显示了)

在xml中配置:

 <bean id="student" class="org.aop.Object.Student">
</bean>


<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(public void org.aop.Object.Student.display())" id="pointcut"/>

</aop:config>
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"

3.通知类实现

注意:

@Aspect		 //声明该类是一个通知
@Before          //前置通知注解
@AfterReturning  //后置通知注解
@AfterThrowing   //异常通知注解
@Around          //环绕通知注解
@After           //最终通知注解
@Component("advice")
@Aspect		//声明该类是一个通知
public class Advice {

	@Before("execution( public void  org.aop.Object.Student.display())") //定义切点  
	public void before(JoinPoint p)
	{
		System.out.println("前置通知!"+"目标对象:"+p.getTarget()+"方法名: "
	+p.getSignature().getName()+"参数个数:"+p.getArgs().length);
	}
	@AfterReturning(pointcut="execution( public void  org.aop.Object.Student.display())",returning="returningValue") 
	public void after(JoinPoint p,Object returningValue)					//声明返回值的参数名
	{
		System.out.println("后置通知!"+returningValue);
	}
	
	@AfterThrowing("execution( public void  org.aop.Object.Student.display())")
	public void exception()
	{
		System.out.println("异常通知!");
	}
	
	@Around("execution( public void  org.aop.Object.Student.display())")
	
	public void around(ProceedingJoinPoint p ) 
	{
		Object result=null;
		try {
			
			System.out.println("环绕通知实现的前置通知!");
			result=p.proceed();
			System.out.println("环绕通知实现的后置通知!");
			
		}
		
		catch(Throwable e)
		{
			
			System.out.println("环绕通知实现的异常通知!");
			
		}
		finally {
			System.out.println("环绕通知实现的最终通知!");
			
		}
	}
		
		@After("execution( public void  org.aop.Object.Student.display())")
		public void fianlly()
		{
			System.out.println("最终通知!");
		}
		
		

通过注解形式 实现的aop如果想获取 目标对象的一些参数,则需要使用一个对象:JointPoint,而在环绕通知中使用ProceedingJoinPoint。


 注解形式的返回值的参数名:一定要声明返回值参数名,否则无法运行

@AfterReturning(pointcut="execution( public void  org.aop.Object.Student.display())",returning="returningValue") 
	public void after(JoinPoint p,Object returningValue)					//声明返回值的参数名

4.继续配置xml

<context:component-scan base-package="org.aop.Log"></context:component-scan>
<!--配置扫描器将通知类注入IOC容器 -->



<aop:aspectj-autoproxy>  <!-- 开启注解对AOP的支持 --> 
</aop:aspectj-autoproxy>

5.运行


  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值