自定义注解
package com.example.spring.controller;
import java.lang.annotation.*;
@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogTest {
String type() default "";
String name() default "";
}
target选择注解可以放在类或者方法上面
retention 什么时候启动注解
切面
@Pointcut 切点,切面什么时候可以切入(切入什么方法)
@Around 环绕加强,有助于对操作前后都操作,必须加上process方法,否则业务代码无法运行
@After 业务跑完之后运行
@AfterThrow 跑完如果抛异常会运行
@AfterReturning(若目标方法无异常,执行@AfterReturning注解方法的业务逻辑)
简单实现
package com.example.spring.controller;标签:String,自定义,System,切面,org,println,import,日志,out From: https://www.cnblogs.com/zzdd/p/17026689.html
import jdk.nashorn.internal.runtime.logging.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
@Component
@Aspect
@Logger
public class AopTest {
@Pointcut("@annotation(com.example.spring.controller.LogTest)")
public void log(){}
@Around("log()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
String name = signature.getName();
LogTest logTest = signature.getMethod().getAnnotation(LogTest.class);
String name1 = logTest.name();
String type = logTest.type();
System.out.println("method:"+method);
System.out.println("name:"+name);
System.out.println("name1:"+name1);
System.out.println("type:"+type);
return joinPoint.proceed();
}
@Before("log()")
public void before(JoinPoint joinPoint){
ServletRequestAttributes signature = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = signature.getRequest();
String ip = request.getRemoteHost();
String remoteUser = request.getRemoteUser();
System.out.println("ip:"+ip);
System.out.println("user"+remoteUser);
}
@After("log()")
public void after(JoinPoint point){
System.out.println("跑完了");
}
@AfterThrowing("log()")
public void after1(JoinPoint joinPoint){
System.out.println("baocuole");
}
}