目錄結構:
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;}
}
瀏覽器返回數據:
http://localhost:8080/list
http://localhost:8080/getone
控制臺打印:
?
?
?
?
?