SpringBoot工程,有不懂的留言or Kimi一下
LogAspect.java
package com.xxx.javaaopdemo.Aspect;import com.xxx.javaaopdemo.LogAnnotation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;import java.lang.reflect.Method;
//标注切面类
@Aspect
@Component
public class LogAspect {//切入注解名字@Pointcut("@annotation(com.xxx.javaaopdemo.LogAnnotation)")public void pointCut(){//找到切点}//绑定上面的pointCut方法@Around("pointCut()")public Object around(ProceedingJoinPoint joinPoint) throws Throwable{//日志方法写到around里面//连接点ProceedingJoinPoint可以区分不同的被切入点方法//获取切点方法名字String name = joinPoint.getSignature().getName();MethodSignature signature = (MethodSignature) joinPoint.getSignature();Method method = signature.getMethod();LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);if (annotation!=null) {//获取注入切点方法注解里面内容valueString value = annotation.value();System.out.println("[System-Logging] : 当前操作 : " + value + " , 执行方法:"+name + "返回值是 = " + joinPoint.proceed());}//切点方法返回值return joinPoint.proceed();}
}
UserController .java
一般是增删改才打日志,所以只在这些个方法上面打了@LogAnnotation,双引号里面就是@LogAnnotation的value(细看@Interface LogAnnotaion的value方法!)
package com.xxx.javaaopdemo.Controller;import com.xxx.javaaopdemo.Entity.User;
import com.xxx.javaaopdemo.LogAnnotation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.Arrays;
import java.util.List;@RestController
@RequestMapping("/user")
public class UserController {@RequestMapping("/list")
// @LogAnnotation("查询用户集合")public List<User> getUserList(){return Arrays.asList(new User(1,"Name1"),new User(2,"Name2"),new User(3,"Name3"));}@GetMapping("/getById/{id}")public User getUserById(@PathVariable("id") Integer id){return new User(id,"Name"+id);}@LogAnnotation("保存")@GetMapping("/save")public boolean save(){return true;}@LogAnnotation("修改")@GetMapping("/edit")public boolean edit(){return true;}@LogAnnotation("通过id删除用户")@GetMapping("/del/{id}")public boolean del(@PathVariable("id")Integer id){return true;}
}
User.java
package com.xxx.javaaopdemo.Entity;import lombok.AllArgsConstructor;
import lombok.Data;@Data
@AllArgsConstructor
public class User {private Integer id;private String name;
}
Aop注解LogAnnotation.java
记得注入
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
package com.xxx.javaaopdemo;import java.lang.annotation.*;@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogAnnotation {String value() default "";
}