1、注解类
import java.lang.annotation.*;
@Target({ElementType.METHOD,ElementType.TYPE}) //作用目标:方法或类上
@Retention(RetentionPolicy.RUNTIME) //注解的生命周期:运行时
@Documented //支持生成文档
@Inherited //支持继承(父类被注解,子类继承后也会被注解)
public @interface MyLog {
String author() default "libai";
}
2、切面
import com.comen.springcloud.annotation.MyLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.stream.Collectors;
@Aspect // <----切面注解
@Component // <----注入IOC容器
@Slf4j
public class MyLogAspect {
//切点
//@within 类上注解
//@annotation 方法上注解
//@不要忘记!!!
//内容为自定义注解的全路径(包名+注解名)
@Pointcut("@within(com.comen.springcloud.annotation.MyLog)||@annotation(com.comen.springcloud.annotation.MyLog)")
public void logPoint() {
}
//前置通知,内容为上述切点
@Before("logPoint()")
public void before() {
log.info("---before---");
}
//后置通知,内容为上述切点
@After("logPoint()")
public void after() {
log.info("---after---");
}
//环绕通知,内容为上述切点
@Around("logPoint()")
public void around(ProceedingJoinPoint joinPoint) throws Throwable {
log.info("---this is before---");
//方法上注解获取注解对象
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
MyLog myLog = joinPoint.getTarget().getClass().getMethod(methodSignature.getName()).getAnnotation(MyLog.class);
if (myLog == null) {
//类上注解获取注解对象
myLog = joinPoint.getTarget().getClass().getAnnotation(MyLog.class);
}
System.out.println("作者是:" + myLog.author());
log.info("---before end---");
joinPoint.proceed();
log.info("---this is after---");
System.out.println("do something ...");
log.info("---after end---");
}
}
3、controller层
import com.comen.springcloud.annotation.MyLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
@MyLog(author = "dufu")
public class FlowLimitController {
@Autowired
private CommonService commonService;
@GetMapping("/testA")
public String testA() // <--dufu
{
log.info("testA");
return "A:"+"------testA";
}
@GetMapping("/testB") // <--libai
@MyLog
public String testB()
{
log.info("testB");
return "B:"+"------testB";
}
@GetMapping("/testC")
@MyLog(author = "baijuyi")
public void testC() // <--baijuyi
{
log.info("testC");
return "C:"+"------testC";
}
}