A preface

By means of the spring AOP functionality, we can apply AOP to global exception handling, global request intercept, etc., the core of this article is using AOP implementation logging, such as which user which operations, this is necessary for a successful project, so the knowledge seeker side gave a simple model application;

2 definition enumeration

Enumeration defines the types of log operations, as shown below. Some are login logs, some are add, delete, change and check logs. Different systems can define different logs, readers can choose;

public enum LogEnum {

    UNOPERATE(0,"Undefined operation"),
    SELECT(1,"Query"),
    INSERT(2,"Add"),
    UPDATE(3,"Update"),
    DELETE(4,"Delete"),
    EXPORT(5,"Excel export"),
    LOGIN(6,"Login"),
    LOGOUT(7,"Logout"),; LogEnum( Integer code, String operate) { this.operate = operate; this.code = code; }LogEnum(){} private String operate; Private Integer code; public StringgetOperate() {
        return operate;
    }

    public void setOperate(String operate) {
        this.operate = operate;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) { this.code = code; }}Copy the code

Three annotations

The purpose of using annotations is to use annotations on which methods, that is, to mark which operations belong to. By combining annotation operation types with defined enumerations, it is easy to implement which operations are performed on which methods.

@Documented @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface MonitorLog { /* * * @author LSC * <p> Log content </p> * @param [] * @return java.lang.String */ String value() default""; /* * * @author LSC * <p> </p> * @param [] * @return int */ LogEnum operateType() default logenum.unoperate; }Copy the code

Four AOP aspects

Set the annotation to the pointcut. By weaving cut points into the cut surface and using surround notification to enhance methods that have been annotated, all annotation actions can be obtained. Then logging into the library can be easily implemented to monitor user logging actions. When the prerequisite is to obtain a user name in AOP, the common Shiro framework has a getSubject method to obtain the user name. Of course, according to the different technology used by different readers to obtain, knowledge seekers in order to simply achieve the function did not use a bunch of tedious methods to achieve a user login authentication system;

/**
 * @Author lsc
 * <p>日志aop切面 </p>
 */

@Aspect
@Component
public class LogAsp {

    /* *
     * @Author lsc
     * <p> 设置切点</p>
     * @Param []
     * @Return void
     */
    @Pointcut("@annotation(com.zszxz.annotation.MonitorLog)")
    public void logPointCut() {} // wrap Around @around ("logPointCut()") public Object around(ProceedingJoinPoint Point) throws Throwable {// Start time LocalDateTime beginTime = LocalDateTime.now(); Object result = point.proceed(); // endTime LocalDateTime endTime = localdatetime.now (); Duration duration = Duration.between(beginTime, endTime); Long seconds = duration.getseconds (); // saveLog saveLog(point,seconds);returnresult; } private void saveLog(ProceedingJoinPoint point, long seconds){ MethodSignature signature = (MethodSignature) point.getSignature(); Method method = signature.getMethod(); MonitorLog = method.getannotation (Monitorlog.class);if(monitorLog! LogEnum operateType = monitorlog.operateType (); String value = monitorlog.value (); System.out.printf("Get action type: %s, get action content: %s",operateType.getCode(),value); Object[] args = point.getargs (); try{ List<Object> objects = Arrays.asList(args); System.out.println(objects); }catch (Exception e){ } } } }Copy the code

5 the presentation layer

This is a method of querying the user, which will be intercepted by AOP when accessing this API;

/**
 * @Author lsc
 * <p> </p>
 */
@RestController
public class UserController {


    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @MonitorLog(value="Query user",operateType = LogEnum.SELECT)
    @GetMapping("zszxz")
    public String getUser(String user){
        return "zszxz"; }}Copy the code

If what do not understand can refer to the source of knowledge seekers (column description or princess number to knowledge seekers github address),