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/>
此文只是简单的介绍了三种用法,详细的大家可以研究一下,咱们一起讨论。