springboot中aop的使用

Spring AOP(Aspect Oriented Programming),即面向切面编程,是OOP(Object Oriented Programming,面向对象编程)的补充和完善。

OOP引入的核心概念包括:封装,继承和多态等;

AOP则可以深入到方法内部,在某个切入点或者切面处采取静态”织入”的方式,在尽量不影响和改动原有代码的基础上,将新功能融入到原有的核心业务逻辑中。

在pom中引入依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

  创建日志注解:

@Documented
@Inherited //注解可被标注类的子类继承
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface TKLog {
    /**
     * 描述
     */
    String description()  default "";
}

  创建aop的处理器:

@Slf4j
@Aspect
@Component
public class LogInterceptor {
    //标注切入点,即标有@TKLog的类
    //@within:拦截被注解标注的类的所有方法,@annotation:拦截被注解的方法
    @Pointcut("@within(com.tk.spring.aop.annotation.TKLog)")
    public void pointcut() {

    }

    //当标有@TKLog的类中的方法被调用前后,该方法会被执行
    @Around("pointcut()")
    public void doExecute(ProceedingJoinPoint point) throws Throwable {
        log.info("方法即将执行:" + point.getSignature().getName());
        Object result = point.proceed();
        log.info("方法执行结束:" + result.toString());
    }
}

  最后在需要的controller层中添加@TKLog注解以及启动类加@EnableAspectJAutoProxy,就可以进行日志打印。

posted @ 2019-08-28 16:44  一生无过  阅读(612)  评论(0编辑  收藏  举报