@Aspect Spring 统一日志管理 详见 http://www.cnblogs.com/chihirotan/p/6228337.html
在pom.xml文件中配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
定义一个类,命名LogAspect,在saveSysLog中执行具体要保存内容操作,ILog 是之前自定义的接口注释,例子中有获取ILog内容、网址ip、请求参数等内容
@Aspect
@Component
public class LogAspect {
@Pointcut("@annotation(com.example.demo.common.annotation.ILog)")
public void saveLogCut(){
}
/**
* 切面记录系统日志
*/
@Around("saveLogCut()")//
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
//执行方法
Object result = point.proceed();
//执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
//保存日志
saveSysLog(point, time);
return result;
}
void saveSysLog(ProceedingJoinPoint joinPoint, long time) throws InterruptedException
{
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
ILog syslog = method.getAnnotation(ILog.class);
if (syslog != null) {
// 注解上的描述
sysLog.setOperation(syslog.value());
}
// 请求的方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
// 请求的参数
Object[] args = joinPoint.getArgs();
try {
String params = new Gson().toJson(args[0]);
} catch (Exception e) {
e.printStackTrace();
}
// 获取request
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
//ip
String ip=IPUtils.getIpAddr(request)
}
}
切面方法说明:
@Aspect -- 作用是把当前类标识为一个切面供容器读取
@Pointcut -- (切入点):就是带有通知的连接点,在程序中主要体现为书写切入点表达式
@Before -- 标识一个前置增强方法,相当于BeforeAdvice的功能
@AfterReturning -- 后置增强,相当于AfterReturningAdvice,方法退出时执行
@AfterThrowing -- 异常抛出增强,相当于ThrowsAdvice
@After -- final增强,不管是抛出异常或者正常退出都会执行
@Around -- 环绕增强,相当于MethodInterceptor