前期準備java
spring3.0版本發佈包裏沒有包含相應的依賴包,因此需手動加入,以下
aspectjrt.jar
aspectjweaver.jar
aopalliance-1.0.jarspring
要想使用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 ">
<!--ui
開啓自動掃描功能,若是類包含 @Component, @Repository, @Service, and @Controller,@Required, @Autowired, @PostConstruct, @PreDestroy, @Resource, @PersistenceContext and
@PersistenceUnit這些註解,將會被spring容易管理,而且提供相應的注入代理
-->
<context:component-scan base-package="sping.*"></context:component-scan>component
<!--xml
開啓基於@AspectJ 的aop,proxy-target-class默認值爲false,基於接口的代理,不然是基於類的代理,依賴cglib包接口
-->
<aop:aspectj-autoproxy proxy-target-class="false"></aop:aspectj-autoproxy>
</beans>
get
聲明一個aop類it
java代碼io
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; } }