這節(jié)內(nèi)容非常關(guān)鍵,我們會比較詳細地介紹Spring AOP注解的使用
- 要使用Spring AOP注解,必須滿足如下的事項
- 導(dǎo)入Aspectj的jar、Spring3.0-AOP.jar、aopalliance.jar
- 需要在配置文件中加入注解的配置,例如:bean-aop-annotiation.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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
如果使用Spring AOP注解,最好的用處就是減少在配置文件中的AOP內(nèi)容。但是如果要掌握好Spring的AOP還需要學(xué)習(xí)注解的語法,下面的內(nèi)容會給大家慢慢介紹
- 織入點語法
package com.spring.aop;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
public class LogAop {
@Before("execution(public void com.spring.dao.impl.StudentDaoImpl.*(..))")
public void logBefore() {
System.out.println("方法執(zhí)行之前轉(zhuǎn)載日志");
}
}
而execution(public void com.spring.dao.impl.StudentDaoImpl.*(..)),這個就是織入點的語法,它告訴AOP框架哪個類中方法需要進行AOP
- execution語法介紹
- execution(public * *(..))
- execution(* set*(..))
- execution(* com.xyz.service.AccountService.*(..))
- execution(* com.xyz.service...(..))
- 上面只是舉例說明了execution的語法,下面是一個標準的語法定義
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)
- Spring AOP注解例子
- @Before前置建議,它是在執(zhí)行一個業(yè)務(wù)方法之前插入的切面
- @AfterReturning,它是當一個方法正常運行后,執(zhí)行的切面
- @After,它是當方法執(zhí)行成功或者出現(xiàn)異常的時候都會執(zhí)行切面
- @Around,它相當于一個AOP鏈,如果當前AOP執(zhí)行后,就讓下一個AOP執(zhí)行
- @AfterThrowing,如果在方法中有錯誤拋出,則執(zhí)行此建議
package com.spring.aop;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
public class LogAop {
@Before("execution(public void com.spring.dao.impl.StudentDaoImpl.*(..))")
public void logBefore() {
System.out.println("方法執(zhí)行之前轉(zhuǎn)載日志");
}
@AfterReturning("execution(public void com.spring.dao.impl.StudentDaoImpl.insert(..))")
public void logAfterReturning() {
System.out.println("方法執(zhí)行返回后載入日志");
}
@After("execution(public * com.spring.dao.impl.StudentDaoImpl.*(..))")
public void logAfter() {
System.out.println("Finally載入日志");
}
@Around("execution(public * com.spring.dao.impl.StudentDaoImpl.*(..))")
public Object doBasicProfiling(ProceedingJoinPointpjp) throws Throwable {
System.out.println("===around建議載入日志===" + new Date());
Object o = pjp.proceed();
return o;
}
@AfterThrowing("execution(public * com.spring.dao.impl.StudentDaoImpl.*(..))")
public void logAfterThrowing() {
System.out.println("===有參數(shù)異常載入日志===" + new Date());
}
}