前期准备
spring3.0版本发布包里没有包含相应的依赖包,所以需手动加入,如下
aspectjrt.jar aspectjweaver.jar aopalliance-1.0.jar要想使用spring aop 须配置xml文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd "> <!--开启自动扫描功能,如果类包含 @Component, @Repository, @Service, and @Controller,@Required, @Autowired, @PostConstruct, @PreDestroy, @Resource, @PersistenceContext and
@PersistenceUnit这些注解,将会被spring容易管理,并且提供相应的注入-->
<context:component-scan base-package="sping.*"></context:component-scan><!--
开启基于@AspectJ 的aop,proxy-target-class默认值为false,基于接口的代理,否则是基于类的代理,依赖cglib包
-->
<aop:aspectj-autoproxy proxy-target-class="false"></aop:aspectj-autoproxy> </beans>声明一个aop类
java代码
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Component(value="logIntercept") @Aspect() public class InterceptOfAspectj { /** * 声明一个切入点,表达式为 "拦截所有返回值类型,所有包下所有方法" */ @Pointcut(value="execution(* sping.beans.service..*.*(..))") public void anyMothed(){ } @Before(value="anyMothed()") public void before(){ System.out.println("前置通知"); } @Before(value="anyMothed()&&args(myname)") public void beforeParam(String myname){ System.out.println("前置通知"+myname); } @AfterReturning(pointcut="anyMothed()",returning="result") public void afrerReturn(Object result){ System.out.println("后置通知"+result); } @After(value="anyMothed()") public void after(){ System.out.println("最后后置通知"); } @AfterThrowing(pointcut="anyMothed()",throwing="e") public void afterThrows(Exception e){ System.out.println("异常通知:"+e.getMessage()); } @Around("anyMothed()") public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable{ System.out.println("环绕通知 开始"); Object obj = pjp.proceed(); System.out.println("环绕通知 结束"); return obj; } }