激活註解
<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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="jee.pk2"></context:component-scan>
<!-- 激活Aspectj註解 -->
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
</beans>
在通知類中加入註解
package jee.pk2;
import org.aspectj.lang.JoinPoint;
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.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class DaoAdvice {
@Pointcut("execution(* jee.pk1.*Impl.*(..))")
public void daoPointcut() {};
@Before("daoPointcut()")
public boolean before(JoinPoint jp) {
System.out.println("前置通知"+jp.getSignature().toLongString()+"方法參數"+jp.getArgs());
return true;
}
@AfterReturning("daoPointcut()")
public void afterReturning() {
System.out.println("after target");
}
@Around("daoPointcut()")
public Object around(ProceedingJoinPoint pjp) {
System.out.println("around before returning");
Object r=null;
try {
r= pjp.proceed();
} catch (Throwable e) {
e.printStackTrace();
System.out.println("arround after throwing target");
}finally {
System.out.println("around after target");
}
System.out.println("around after returning target");
return r;
}
@After("daoPointcut()")
public void after() {
System.out.println("after target");
}
@AfterThrowing("daoPointcut()")
public void afterTrowing() {
System.out.println("after throwing");
}
}