1.aop是什麼
AOP是Aspect Oriented Programming的縮寫,意思是面向切面編程,與OOP(Object Oriented Programming)面向對象編程對等,都是一種編程思想。
從OOP角度分析,我們關注業務的處理邏輯,是屬於縱向的行為,從AOP角度分析,我們關注對象行為發生時的問題,是屬於橫向的行為。
2.AOP 作用:
2.1 監控函數的調用
2.2 捕獲異常發生
實際應用在:事務、安全、日志等橫切關注。
下面是aop打印service層的方法日志為例:各個注解很好理解,執行前執行後等
@Component
@Aspect
public class ApiServiceAspect {
private final Logger logger = Logger.getLogger(this.getClass());
/**
* 切面
*/
private final String POINT_CUT = "execution(* com.demo.service.*.*.*(..))";
@Pointcut(POINT_CUT)
private void pointcut(){}
@Before(value = POINT_CUT)
public void before(JoinPoint joinPoint) {
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
StringBuilder log = new StringBuilder();
log.append("before: ")
.append(className)
.append("@")
.append(methodName)
.append(" , params: ");
Object[] args = joinPoint.getArgs();
for (Object arg : args) {
log.append(JSONObject.toJSONString(arg) + ", ");
}
logger.info(log.toString());
}
@AfterReturning(value = "pointcut()", returning = "returnObj")
public void afterReturn(Object returnObj) {
String result = JSONObject.toJSONString(returnObj);
logger.info("afterReturning: "+result);
}
@AfterThrowing(value = POINT_CUT, throwing = "e")
public void afterThrowing(Throwable e) {
logger.error("afterThrowing: "+e.getMessage(), e);
}
@Around(value = "pointcut()")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
Long begin = System.currentTimeMillis();
StringBuilder log = new StringBuilder("around: ");
Object result = null;
try {
result = proceedingJoinPoint.proceed();
} catch (Exception e) {
logger.error(log + e.getMessage(), e);
}
Long end = System.currentTimeMillis();
log.append(" 執行時間: ")
.append(end-begin)
.append("ms");
return result;
}
}
3.配置文件
<context:component-scan base-package="com.jjshome.bigdata" />
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
如果使用了spring mvc後,如果把<aop:aspectj-autoproxy proxy-target-class="true"/>放在application.xml文件中可能會aop無效,最好把它放在dispatcher-servlet.xml文件中