在这篇文章中,原来理解AOP这么简单 我们用简单的例子理解了AOP,今天用一个小demo,看看怎么实现!
自定义注解
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogAnnotaion {
String module() default "";
String operator() default "";
}
定义切面
@Component //能够让spring找到它
@Aspect //切面 定义了通知和切点的关系
@Slf4j
public class LogAspect {
@Pointcut("@annotation(com.example.aopdemo.LogAnnotaion)")//切点
// @Pointcut("execution(public * com.example.aopdemo.AopService.*)")//类里所有方法都是切点
public void pt() {
}
//环绕通知
@Around("pt()")
public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
long beginTime = System.currentTimeMillis();
Object result = joinPoint.proceed();
long endTime = System.currentTimeMillis();
recordLog(joinPoint, endTime - beginTime);
return result;
}
@Before("pt()")
public void logBefore(JoinPoint joinPoint) throws Throwable {
log.info("方法执行之前"+joinPoint.getArgs().toString());
}
@After("pt()")
public void logAfter() throws Throwable {
log.info("方法执行之后");
}
private void recordLog(ProceedingJoinPoint joinPoint, long l) {
System.out.println();
log.info("执行方法"+joinPoint.getTarget().getClass().getName() +"====执行时间:==="+ l);
}
}
Controller
@RestController
@RequestMapping("/api")
public class AopController {
@Autowired
private AopService aopService;
@GetMapping("/getName")
public String getName(String name){
return aopService.getName(name);
}
}
Service 添加自定义注解
@Service
@Slf4j
public class AopService {
@LogAnnotaion(module = "检查项", operator = "添加检查项")
public String getName(String name){
log.info("方法执行之中");
return name;
}
}