zoukankan      html  css  js  c++  java
  • Spring学习之AOP的实现方式

    Spring学习之AOP的三种实现方式

    一、介绍AOP

    在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

    需要了解一下名词:

    • 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 ....
    • 切面(ASPECT):横切关注点 被模块化 的特殊对象。即,它是一个类。
    • 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
    • 目标(Target):被通知对象。
    • 代理(Proxy):向目标对象应用通知之后创建的对象。
    • 切入点(PointCut):切面通知 执行的 “地点”的定义。
    • 连接点(JointPoint):与切入点匹配的执行点。

    简单来说就是不改变原来代码的情况下增加新功能的方式。

    二、三种实现方式

    设定通过在具体的业务实现方法前后增加输出日志的功能来实现AOP的功能

    首先需要导入依赖包

    <dependencies>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.2</version>
        </dependency>
    </dependencies>
    

    第一种通过 Spring API 实现

    首先编写业务接口和实现类

    public interface UserService {
        void add();
        void delete();
        void update();
        void select();
    }
    
    public class UserServiceImpl implements UserService {
        @Override
        public void add() {
            System.out.println("增加了一个用户!");
        }
    
        @Override
        public void delete() {
            System.out.println("删除了一个用户!");
        }
    
        @Override
        public void update() {
            System.out.println("更新了一个用户!");
        }
    
        @Override
        public void select() {
            System.out.println("查询了一个用户!");
        }
    }
    

    编写两个打印日志的实现类
    一个是实现API的 MethodBeforeAdvice 方法,实现执行方法之前的日志输出

    import org.springframework.aop.MethodBeforeAdvice;
    import java.lang.reflect.Method;
    
    public class BeforeLog implements MethodBeforeAdvice {
        // method:要执行目标对象的方法
        // args:参数
        // target:目标对象
        @Override
        public void before(Method method, Object[] args, Object target) throws Throwable {
            System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
        }
    }
    

    另一个是API的 AfterReturningAdvice 方法,实现执行方法之后的日志输出

    import org.springframework.aop.AfterReturningAdvice;
    import java.lang.reflect.Method;
    
    public class AfterLog implements AfterReturningAdvice {
        // returnValue:返回值
        @Override
        public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
            System.out.println("执行了"+method.getName()+"的方法,返回结果为:"+returnValue);
        }
    }
    

    然后去applicationContext.xml配置文件中注册bean以及配置切入方式

    <!--方式一:使用spring原生API接口-->
    <!--注册bean-->
    <bean id="userService" class="com.tioxy.service.UserServiceImpl"/>
    <bean id="afterLog" class="com.tioxy.log.AfterLog"/>
    <bean id="beforeLog" class="com.tioxy.log.BeforeLog"/>
    <!--配置AOP-->
    <aop:config>
        <!--切入点:就是在哪里执行方法
        expression:表达式
        execution(要执行的位置)
        -->
        <aop:pointcut id="pointcut" expression="execution(* com.tioxy.service.UserServiceImpl.*(..))"/>
    
        <!--执行环绕增强-->
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
    </aop:config>
    

    最后进行测试

    public class Mytest {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            UserService userService = context.getBean("userService", UserService.class);
            userService.add();
    
        }
    }
    

    第二种自定义类来实现Aop

    业务接口和实现类还是 UserService 和 UserServiceImpl

    编写自定义实现类

    public class DiyPointCut {
        public void before(){
            System.out.println("=============方法执行前============");
        }
    
        public void after(){
            System.out.println("=============方法执行后============");
        }
    }
    

    然后去applicationContext.xml配置文件中注册bean以及配置切入方式

    <!--第二种方式自定义实现-->
    <!--注册bean-->
    <bean id="diy" class="com.kuang.config.DiyPointcut"/>
    
    <!--aop的配置-->
    <aop:config>
       <!--第二种方式:使用AOP的标签实现-->
       <aop:aspect ref="diy">
           <aop:pointcut id="diyPonitcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
           <aop:before pointcut-ref="diyPonitcut" method="before"/>
           <aop:after pointcut-ref="diyPonitcut" method="after"/>
       </aop:aspect>
    </aop:config>
    

    然后进行测试

    public class Mytest {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            UserService userService = context.getBean("userService", UserService.class);
            userService.add();
    
        }
    }
    

    第三种使用注解方式实现Aop

    编写一个注解方式的实现类

    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.After;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    
    @Aspect
    public class AnnotationPointcut {
       @Before("execution(* com.kuang.service.UserServiceImpl.*(..))")
       public void before(){
           System.out.println("---------方法执行前---------");
      }
    
       @After("execution(* com.kuang.service.UserServiceImpl.*(..))")
       public void after(){
           System.out.println("---------方法执行后---------");
      }
    }
    

    然后去applicationContext.xml配置文件中注册bean以及配置切入方式

    <!--方式三:使用注解-->
    <bean id="annotationPointCut" class="com.tioxy.diy.AnnotationPointCut"/>
    <!--开启注解支持-->
    <aop:aspectj-autoproxy/>
    

    最后进行测试

    以上就是AOP的三种实现方式

    文章引用
    狂神说Java:https://www.bilibili.com/video/BV1WE411d7Dv?p=20

  • 相关阅读:
    - (NSString *)description
    3.30 学习笔记
    常用的 博客
    iOS 比较好的博客
    iOS查看一段代码运行的时间
    tableview 第一次可以查看tableview 当退出第二次却会出现Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:]
    iphone 设置全局变量的几种方法
    java操作控件加密
    关闭windows 警报提示音
    HttpServletRequest简述
  • 原文地址:https://www.cnblogs.com/tioxy/p/13188264.html
Copyright © 2011-2022 走看看