aop本質就就是動態代理。
aop的註解開發配置:<aop:aspectj-autoproxy />
通知類型介紹
try{
前置通知(@Before)
result=method.invoke(targetObject,args);
後置通知(@AfterReturning)
}catch(RuntimeException e){
例外通知(@AfterThrowing)
}finally{
最終通知(@After)
}
環繞通知(@Around)
基於註解的開發:
/**
* 定義切面,對所有的controller添加日誌
*/
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
@Aspect
@Component
public class WebLogAspect {
private static final Logger LOG = LoggerFactory.getLogger(WebLogAspect.class);
//匹配com.springboot.first.controller下的所有public方法
@Pointcut("execution(public * com.springboot.first.controller.*.*(..))")
public void logPointCut() {
}
@Before("logPointCut()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 接收到請求,記錄請求內容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 記錄下請求內容
LOG.info("請求地址 : " + request.getRequestURL().toString());
LOG.info("HTTP METHOD : " + request.getMethod());
LOG.info("IP : " + request.getRemoteAddr());
LOG.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "."
+ joinPoint.getSignature().getName());
LOG.info("參數 : " + Arrays.toString(joinPoint.getArgs()));
}
@AfterReturning(returning = "ret", pointcut = "logPointCut()")// returning的值和doAfterReturning的參數名一致
public void doAfterReturning(Object ret) throws Throwable {
// 處理完請求,返回內容
LOG.info("返回值 : " + ret);
}
@Around("logPointCut()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
long startTime = System.currentTimeMillis();
Object ob = pjp.proceed();// ob 爲方法的返回值
LOG.info("耗時 : " + (System.currentTimeMillis() - startTime));
return ob;
}
}
execution表達式
execution("* com.springboot.first.controller.*.*(..)")
第一個*號表示所有的返回值都可以。
第一個.表示包下的所有類,..表示包下的子類和子包下的子類
第二個*表示所有的類
第三個*表示類裏的所有方法
()表示方法形參內參數
()內的..表示任何參數都可以
若只攔截返回值爲String類型的方法則寫成:
execution("java.lang.String com.springboot.first.controller.*.*(..)")
若只攔截返回值不爲void類型的方法則寫成:
execution("!void com.springboot.first.controller.*.*(..)")
基於xml配置的開發:
<bean id="webLogAspect" class="com.springboot.first.aop.WebLogAspect"></bean>
<aop:config>
<aop:aspect id="aop" ref="webLogAspect">
<aop:pointcut id="logPointCut" expression="execution(public * com.springboot.first.controller.*.*(..))"/>
<aop:before method="doBefore" pointcut-ref="logPointCut"/>
<aop:after-returning method="doAfterReturning" pointcut-ref="logPointCut" returning="ret"/>
<aop:around method="doAround" pointcut-ref="logPointCut"/>
</aop:aspect>
</aop:config>
測試結果: