定義切面類
```
@Component
@Aspect
public class LogAspect {
/* @Pointcut("execution(* com.neuedu.aop.business.*.*(..))")
public void anyMethod()
{
}
@Before("execution(* com.neuedu.aop.business.*.*(..))")
public void before()
{
System.out.println("方法開始了");
}
@After("execution(* com.neuedu.aop.business.*.*(..))")
public void after()
{
System.out.println("方法結束了");
}
@AfterThrowing(pointcut="anyMethod()",throwing="ex")
public void exception(Exception ex)
{
System.out.println("方法拋出異常了");
//記錄在日志文件。
ex.printStackTrace();
}
@AfterReturning(pointcut="anyMethod()",returning="str")
public void afterreturnning(String str)
{
System.out.println(str);
System.out.println("方法正常結束");
}*/
@Around("execution(* com.neuedu.aop.business.*.*(..))")
public void round(ProceedingJoinPoint jp)
{
//before通知
//1. 獲得當前時間
Date d1 = new Date();
System.out.println(jp.getSignature().getName()+"開始了");
try
{
jp.proceed();//執行目標方法
}
catch(Throwable e)
{
//記日志 after throwing
System.out.println(e.getMessage());
}
//after
System.out.println(jp.getSignature().getName()+"結束了");
//2. 獲得當前時間
Date d2 = new Date();
System.out.println("方法運行,耗時:"+ (d2.getTime() - d1.getTime()));
}
}
```
applicationContext.xml
```
<!-- 啟用注解方式的aop -->
<!-- 默認值:proxy-target-class="false" 使用jdk的代理模式, 特殊注意:如果沒有實現接口,自動調用cglib的方式-->
<!-- proxy-target-class="true" 使用cglib增強模式,有沒有接口都支持 -->
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
<context:component-scan base-package="com.neuedu.aop"></context:component-scan>
```
測試類的實現:
```
@Test
public void testAOP1()
{
//啟動ioc容器
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//
TestAspect testAspect = ctx.getBean(TestAspect.class);
testAspect.test();
//spring aop的實現基于動態代理的設計模式
//1。被代理類需要實現一個接口(TestAspect implements ITestAspect)-> JDK自帶功能(調用相應的類,方法,就可以自己寫這種動態代理)
//2.被代理類不需要實現接口,aop生成目標類的子類。-》 JDK不支持,第三方工具cglib支持(調用相應的類,方法,就可以自己寫這種動態代理)。
//3. aspectj靜態織入,直接修改目標類的class文件,更靈活
//spring引入aspectj,目的是使用aspectj注解語法(aspect,before),內部機制仍然是動態代理, 即第一種和第二種。
}
```