美文网首页
spring-aop

spring-aop

作者: 冬季洛阳 | 来源:发表于2017-06-14 18:49 被阅读0次

    aop概念

    AOP为Aspect Oriented Programming的缩写,意为:面向切面编程

    aop术语

    joinpoint连接点:类中可以被增强的方法(其实就是类中的方法)
    pointcut切入点:类中实际被增强的方法(并不是所有的方法都被增强了)

    advice通知/增强:实际扩展功能的逻辑,有下面几种类型

    前置增强 before 方法执行之前

    后置增强 after方法执行之后

    异常增强 @AfterThrowing 出现异常的时候

    最终增强 在后置之后执行

    环绕增强 around 方法之前和之后执行

    aspect切面:把增强用到切入点的过程

    target目标:被增强方法所在的类

    weaving织入:将增强应用到目标的过程

    AOP

    Spring实现aop操作有两种方式:1、Spring-aop 2、AspectJ

    spring-aop(使用xml文件配置)

    1、导包

    spring-aop.jar、aspectjweaver.jar

    常用表达式

    execution(<访问修饰符>?<返回类型><方法名>(<参数>)<异常>)
     1.execution(* com.hemi.aop.Coffee.drink())
     2. execution(* com.hemi.aop.Coffee.drink(..))
     3. execution(* com.hemi.aop.Coffee.(..))
     4. execution(
    .(..))
     5. execution(* add*(..)) 所有add开头的方法

    <!-- 被增强的类 -->              
        <bean class="com.hemi.bean.Car" id="car"></bean>
        <!-- 实施增强的类 -->
        <bean class="com.hemi.bean.CarUtils" id="carUtils"></bean>
    
        <!-- 配置aop -->
        <aop:config>    
            <!-- 切入点:被增强的方法 -->
            <aop:pointcut expression="execution(public void com.hemi.bean.Car.run(..))" id="pointcut1"/>
            <!-- 切面:将切面运用到切入点的过程 -->
            <aop:aspect ref="carUtils">
                <aop:before method="show" pointcut-ref="pointcut1"/>
            </aop:aspect>
        </aop:config>
    
    
    环绕增强
        @Around("pointcut()")
        public void around(ProceedingJoinPoint p) throws Throwable {
            //用around必须导入roceedingJoinPoint
            long time1 = System.currentTimeMillis();
            p.proceed();
            long time2 = System.currentTimeMillis();
            System.out.println("行驶时间:"+(time2 - time1));
        }
    

    AspectJ

    1、导包 spring-aspectj.jar、aspectjweaver.jar

    2、通过xml文件开启aspectj注解

    <aop:aspectj-autoproxy/>

    <context:component-scan base-package="com.hemi.bean"></context:component-scan>//其他注解的扫描
    3、创建增强类

    @Aspect//标示该类是增强类
    @Service
    public class StudentUtils {
        //配置切入点,括号内是表达式
        @Pointcut("execution(* com.hemi.bean.Student.study(..))")
        public void pointcut(){}
    
        //前置增强,括号内写切入点的名称,即上面的方法名
        @Before("pointcut()")
        public void high(){
            System.out.println("玩会手机。。。。");
        }
    }
    

    注意:检查好execution里的括号,切点也可以直接放到增强里面

    相关文章

      网友评论

          本文标题:spring-aop

          本文链接:https://www.haomeiwen.com/subject/wydeqxtx.html