Spring aop实现的三种方式

Spring aop的重要性:

        Spring aop将公共业务(如日志等)和其他模块业务结合,减少了代码的书写,加快了程序猿开发效率,实现了公共业务的重复利用,使得系统更加的模块化。

        Spring aop其底层是动态代理实现的,aop将其封装,让程序猿使用的更加方便。

导入的额外包:

         aopaliance.jar

         aspectjweaver.jar

实现方法1:使用aop API

切面的实现类:

public class Log implements AfterReturningAdvice{

	@Override
	public void afterReturning(Object returnValue, Method arg1, Object[] arg2, Object target) throws Throwable {
		System.out.println("返回值为:"+returnValue+"执行了"+arg1+"方法"+"参数为:"+arg2+"目标对象为:"+target);
	}
}


实现接口AfterReturningAdvice(后置通知)。

其中还包括:前置通知(BeforeAdvice),异常通知(ThrowsAdvice)。

配置文件:

<aop:config>
        <aop:pointcut expression="execution(* com.lsw.spring4_aop1.service.UserServiceImpl.*(..))" id="pointcut"/>
       <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
</aop:config>

实现方法2:自定义类实现aop

自定义类:(切面)

public class Log{
	public void before(){
		System.out.println("执行方法之前");
	}
	
	public void after(){
		System.out.println("执行方法之后");
	}
}

配置文件:

        <aop:config>
        	<aop:aspect ref="log"><!-- ref:连接的是自定义类 -->
        		<aop:pointcut expression="execution(* com.lsw.spring4_aop2.service.impl.*.*(..))" id="pointcut"/>
        		<aop:before method="before" pointcut-ref="pointcut"/>
        		<aop:after method="after" pointcut-ref="pointcut"/>
        	</aop:aspect>
        </aop:config>
实现方法3:注解实现aop

切面实现:

@Aspect
public class Log{
	
	@Before("execution(* com.lsw.spring4_aop2.service.impl.*.*(..))")
	public void before(){
		System.out.println("执行方法之前");
	}
	
	@After("execution(* com.lsw.spring4_aop2.service.impl.*.*(..))")
	public void after(){
		System.out.println("执行方法之后");
	}
	@Around("execution(* com.lsw.spring4_aop2.service.impl.*.*(..))")
	public Object around(ProceedingJoinPoint pj) throws Throwable{
		System.out.println("环绕前");
		System.out.println("签名:"+pj.getSignature());
		Object result=pj.proceed();
		System.out.println("环绕后");
		return result;
	}
}
在类的声明前,添加注解@Aspect,然后在方法前依次添加需要的注解。

配置文件十分简单,只需要加上:<aop:aspectj-autoproxy/>

此文只是简单的介绍了三种用法,详细的大家可以研究一下,咱们一起讨论。


      

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值