目录结构:
1、创建springboot项目,添加依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2、自定义注解@Log
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 Log {
String value() default "";
}
3、设置切面
import com.wzq.log.annotation.Log;
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.wzq.log.annotation.Log)")
public void logPointCut() {
}
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable, InterruptedException {
System.out.println("=============================");
Object result = point.proceed();
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
String name = method.getName();
System.out.println("Method Name:" + name);//输出方法名
Log log = method.getAnnotation(Log.class);
System.out.println("Log Value:" + log.value());//输出注解里面的值
System.out.println("+++++++++++++++++++++++++++++");
return result;
}
}
4、Controller用户测试效果
import com.wzq.log.annotation.Log;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@RestController
public class TestController {
@GetMapping("/list")
@Log("获取Student列表")
public List list() {
List list = new ArrayList();
for(int i = 0 ; i < 10 ; i++){
Student student = new Student();
student.setId(i);
student.setName("name"+i);
list.add(student);
}
return list;
}
@GetMapping("/getone")
@Log("获取Student")
public Student success() {
Student student = new Student();
student.setId(10);
student.setName("name"+10);
return student;
}
}
class Student implements Serializable {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
浏览器返回数据:
控制台打印: