springboot 自定义注解+AOP 实现日志记录
2017-11-24 12:43
1186 查看
一.自定义注解
package com.xiaojukeji.common.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface SystemLogAnnotation { String value(); }
(1)
@Target注解是标注这个类它可以标注的位置,常用的元素类型(ElementType):
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
// TYPE类型可以声明在类上或枚举上或者是注解上
TYPE,
/** Field declaration (includes enum constants) */
// FIELD声明在字段上
FIELD,
/** Method declaration */
// 声明在方法上
METHOD,
/** Formal parameter declaration */
// 声明在形参列表中
PARAMETER,
/** Constructor declaration */
// 声明在构造方法上
CONSTRUCTOR,
/** Local variable declaration */
// 声明在局部变量上
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE,
/** * Type parameter declaration * * @since 1.8 */
TYPE_PARAMETER,
/** * Use of a type * * @since 1.8 */
TYPE_USE
}
(2)
@Retention注解表示的是本注解(标注这个注解的注解保留时期)
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
// 源代码时期
SOURCE,
/**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
*/
// 字节码时期, 编译之后
CLASS,
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
// 运行时期, 也就是一直保留, 通常也都用这个
RUNTIME
}
(3)
@Documented是否生成文档的标注, 也就是生成接口文档是, 是否生成注解文档
二.AOP切面类---此处我用后置通知package com.xiaojukeji.ecm.aop;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import nl.bitwalker.useragentutils.UserAgent;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
febe
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.xiaojukeji.common.annotation.SystemLogAnnotation;
import com.xiaojukeji.dao.model.SystemLog;
import com.xiaojukeji.ep.ip.common.model.AdUser;
import com.xiaojukeji.ep.ip.common.utils.ContextHolder;
import com.xiaojukeji.service.ERPService;
import com.xiaojukeji.service.SystemLogService;
/**
* <p>Description: [用户操作日志AOP]</p>
* Created on 2017年11月24日 上午10:32:35
* @author <a href="mailto: 15175223269@163.com">全冉</a>
* @version 1.0
* Copyright (c) 2017 全冉公司
*/
@Component
@Aspect
//@Order(1)标记切面类的处理优先级,i值越小,优先级别越高.PS:可以注解类,也能注解到方法上
public class EcmSysemLogAop {
private static final Logger LOGGER = LoggerFactory.getLogger(EcmSysemLogAop.class);
@Autowired
private ERPService erpService;
@Resource
private SystemLogService systemLogService;
/**
* <p>Discription:[后置通知,扫描com.xiaojukeji包及此包下的所有带有SystemLogAnnotation注解的方法]</p>
* Created on 2017年11月24日 上午10:28:34
* @param joinPoint 前置参数
* @param systemLogAnnotation 自定义注解
* @author:[全冉]
*/
@After(("execution(* com.xiaojukeji..*.*(..)) && @annotation(systemLogAnnotation)"))
public void doAfterAdvice(JoinPoint joinPoint, SystemLogAnnotation systemLogAnnotation) {
LOGGER.info("=========================================用户操作日志-后置通知开始执行......=========================================");
String value = systemLogAnnotation.value();
addSystemLog(value);
LOGGER.info("=========================================用户操作日志-后置通知结束执行......=========================================");
}
/**
* <p>Discription:[保存操作日志]</p>
* Created on 2017年11月20日 下午3:07:33
* @param operationContent 操作内容
* @author:[全冉]
*/
public void addSystemLog(String operationContent) {
// 获取此次请求的request对象
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
// 获取当前登录人的信息
AdUser adUser = ContextHolder.getInstance().getCurrentUser();
adUser = erpService.getAdUser(adUser);
// 员工号
String employeeNum = adUser.getEmplID();
// 员工姓名
String employeeName = adUser.getEmplName();
// 邮箱
String employeeEmail = adUser.getEmailAddr();
// 浏览器标标识
String webIdentifiy = getBrowserInfo(request);
SystemLog systemLog = new SystemLog();
systemLog.setEmployeeNum(employeeNum);
systemLog.setEmployeeName(employeeName);
systemLog.setEmployeeEmail(employeeEmail);
systemLog.setOperationContent(operationContent);
systemLog.setWebIdentifiy("浏览器" + webIdentifiy);
systemLogService.save(systemLog);
}
/**
* <p>Discription:[根据request获取前台浏览器标识]</p>
* Created on 2017年11月20日 下午7:30:08
* @param request request对象
* @return String 浏览器标识
* @author:[全冉]
*/
private static String getBrowserInfo(HttpServletRequest request) {
UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
String browserInfo = userAgent.getBrowser().toString();
return browserInfo;
}
}[b]三.将自定义注解@SystemLogAnnotation用在切面的方法上[/b]
package com.xiaojukeji.ecm.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import springfox.documentation.annotations.ApiIgnore; import com.xiaojukeji.common.annotation.SystemLogAnnotation; import com.xiaojukeji.dao.model.Terminal; import com.xiaojukeji.service.TerminalService; /** * Description: [设备管理controller] * Created on 2017年11月09日 * @author <a href="mailto: 15175223269@163.com">全冉</a> * @version 1.0 * Copyright (c) 2017年 全冉公司 */ @Api(value = "导出相关接口", description = "导出相关接口") @RestController @RequestMapping("/export") public class ExportController { @Resource private TerminalService terminalService; /** * <p>Discription:[导出设备管理数据]</p> * Created on 2017年11月09日 * @param terminal 设备实体类 * @param response 响应参数 * @author:全冉 */ @GetMapping("/exportTerminal") @ApiOperation(value = "导出设备管理数据") @ApiImplicitParams({ @ApiImplicitParam(name = "macAddress", value = "mac地址", required = false, paramType = "query"), @ApiImplicitParam(name = "officeBuildingName", value = "办公区", required = false, paramType = "query"), @ApiImplicitParam(name = "type", value = "1:终端机 2:ipad", required = false, paramType = "query"), }) @SystemLogAnnotation("导出设备数据") public synchronized void exportTerminal(@ApiIgnore() Terminal terminal, HttpServletResponse response) { try { this.terminalService.exportTerminal(terminal, response); }catch (Exception e) { e.printStackTrace(); } } }
四.启动项目,请求此controller里的导出方法,在此方法的return前执行后置操作,既记录日志。
五.注解讲解:
类注解:@Aspect将一个类定义为一个切面类
@order(i)标记切面类的处理优先级,i值越小,优先级别越高.PS:可以注解类,也能注解到方法上
方法注解:@Pointcut定义一个方法为切点里面的内容为一个表达式,下面详细介绍
@Before 在切点前执行方法,内容为指定的切点
@After 在切点后,return前执行,
@AfterReturning在切入点,return后执行,如果想对某些方法的返回参数进行处理,可以在这操作
@Around 环绕切点,在进入切点前,跟切点后执行
@AfterThrowing 在切点后抛出异常进行处理
@order(i) 标记切点的优先级,i越小,优先级越高
@Pointcut注解组合使用:上面代码中,我们定义了一个切点,该切点只进行处理指定路径的:
@Pointcut("execution(public * com.example.DemoApplication.*(..))") private void controllerAspect(){}现在,我们在定义一个处理其他路径下的切点:
@Pointcut("execution(public * com.demo.*.*(..))") private void controllerDemo(){}以上切点,都是分别处理不同的内容,如果我们需要一个切点来处理他们两者,我们可以这么配置:
@Pointcut(value = "controllerAspect() || controllerDemo()") private void all(){}在@Pointcut注解内,直接引用其它被@Pointcut注解过的方法名称,这样,该切点就可以处理两个路径下的方法
在多个execution表达式之间使用 ||,or表示 或,使用 &&,and表示 与,!表示 非.
execution(* com.travelsky.ccboy.dao..*.find*(..)) || execution(* com.travelsky.ccboy.dao..*.query*(..))
@Pointcut注解中的execution表达式: public * com.demo.*.*(..)第一个 public 表示方法的修饰符,可以用*代替
第一个 * 表示 返回值,*代表所有
com.demo.* 包路径,.*表示路径下的所有包
第三个.* 表示路径下,所有包下的所有类的方法
(..) 表示不限方法参数
关于@order(i)注解的一些注意事项:注解类,i值是,值越小,优先级越高
注解方法,分两种情况
注解的是 @Before 是i值越小,优先级越高
注解的是 @After或者@AfterReturning 中,i值越大,优先级越高
总结两者的概括就是:
在切入点前的操作,按order的值由小到大执行
在切入点后的操作,按order的值由大到小执行
相关文章推荐
- springboot aop 自定义注解方式实现一套完善的日志记录(完整源码)
- Spring AOP实现复杂的日志记录(自定义注解)
- 使用自定义注解+Spring AOP 实现日志记录
- Spring+SpringMVC+Mybatis 利用AOP自定义注解实现可配置日志快照记录
- spring aop自定义注解实现日志记录
- Spring+SpringMVC+Mybatis 利用AOP自定义注解实现可配置日志快照记录
- Spring AOP自定义注解实现系统日志记录管理
- Spring+SpringMVC+Mybatis 利用AOP自定义注解实现可配置日志快照记录
- SpringBoot使用自定义注解+拦截器 实现日志记录
- 从头认识Spring-3.6 简单的AOP日志实现(注解版)-需要记录方法的运行时间
- SpringAOP拦截Controller,Service实现日志管理(自定义注解的方式)
- 自定义注解和aop结合使用---自定义日志记录的实现
- SpringMVC利用AOP实现自定义注解记录日志
- SpringAOP拦截Controller,Service实现日志管理(自定义注解的方式)
- springAOP自定义注解方式实现日志管理
- SpringAOP拦截Controller,Service实现日志管理(自定义注解的方式)
- 从头认识Spring-3.8 简单的AOP日志实现(注解版)-扩展增加检查订单功能,以便记录并检测输入的参数
- SpringMVC利用AOP实现自定义注解记录日志
- SpringAOP拦截Controller,Service实现日志管理(自定义注解的方式)
- spring自定义注解实现AOP日志管理