zoukankan      html  css  js  c++  java
  • 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,就可以进行日志打印。

  • 相关阅读:
    对线程的理解
    C#-设计模式-策略模式
    C#-设计模式-观察者模式
    C#-设计模式-模板方法
    C#-设计模式-适配器模式
    C#-设计模式-代理模式
    C#-设计模式-装饰模式
    C#-设计模式-简单工厂
    C#-设计模式-单例模式
    DotNet Core2.1 编写自己的中间件和后台服务
  • 原文地址:https://www.cnblogs.com/dinghaoran/p/11424943.html
Copyright © 2011-2022 走看看