springaop对service层⽇志和异常的处理
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 = Class());
/**
* 切⾯
*/
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 = Target().getClass().getName();
String methodName = Signature().getName();
StringBuilder log = new StringBuilder();
log.append("before: ")
.append(className)
.append("@")
.append(methodName)
.append(" , params: ");
Object[] args = Args();
for (Object arg : args) {
log.JSONString(arg) + ", ");
}
logger.String());
}
@AfterReturning(value = "pointcut()", returning = "returnObj")
public void afterReturn(Object returnObj) {
String result = JSONString(returnObj);
logger.info("afterReturning: "+result);
}
@AfterThrowing(value = POINT_CUT, throwing = "e")
public void afterThrowing(Throwable e) {
("afterThrowing: "+e.getMessage(), e);
long spring是什么意思
}
@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) {
(log + e.getMessage(), e);
}
Long end = System.currentTimeMillis();
log.append(" 执⾏时间: ")
.append(end-begin)
.append("ms");
return result;
}
}
3.配置⽂件
<context:component-scan base-package="com.demo" />
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
如果使⽤了spring mvc后,如果把<aop:aspectj-autoproxy proxy-target-class="true"/>放在l⽂件中可能会aop⽆效,最好把它放在l⽂件中
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论