统一异常处理
在controller里创建advice包,创建ExceptionAdvice类
这个注解括号里面是指只扫描被@Controller标注的bean
请求request、响应response、异常exception
普通请求和异步请求的区别在于传的是json还是html吗?
统一记录日志
面向切面编程:
程序之中已经开发好了处理逻辑的一个一个Bean
目标对象有很多地方Joinpoint可以织入代码
AOP定义了一个方面组件Aspect, 需要Pointcut切点声明到底织入哪些对象哪些位置(找坐标),Advice通知组件声明组件具体的逻辑是什么(写逻辑)
SpringAOP只支持方法类型的连接点
//@Component
//@Aspect
public class AlphaAspect {@Pointcut("execution(* com.nowcoder.community.service.*.*(..))")public void pointcut() {}@Before("pointcut()")public void before() {System.out.println("before");}@After("pointcut()")public void after() {System.out.println("after");}@AfterReturning("pointcut()")public void afterRetuning() {System.out.println("afterRetuning");}@AfterThrowing("pointcut()")public void afterThrowing() {System.out.println("afterThrowing");}@Around("pointcut()")public Object around(ProceedingJoinPoint joinPoint) throws Throwable {System.out.println("around before");Object obj = joinPoint.proceed();System.out.println("around after");return obj;}}
这个织入的逻辑会被织入代理逻辑里面,以后调用代理对象不是原始对象
在方法执行之前调用日志
@Component
@Aspect
public class ServiceLogAspect {private static final Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);@Pointcut("execution(* com.nowcoder.community.service.*.*(..))")public void pointcut() {}@Before("pointcut()")public void before(JoinPoint joinPoint) {// 用户[1.2.3.4],在[xxx],访问了[com.nowcoder.community.service.xxx()].ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request = attributes.getRequest();String ip = request.getRemoteHost();String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());String target = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();logger.info(String.format("用户[%s],在[%s],访问了[%s].", ip, now, target));}}