spring-aop

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里的括号,切点也可以直接放到增强里面

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 基本知识 其实, 接触了这么久的 AOP, 我感觉, AOP 给人难以理解的一个关键点是它的概念比较多, 而且坑爹...
    永顺阅读 8,329评论 5 114
  • **** AOP 面向切面编程 底层原理 代理!!! 今天AOP课程1、 Spring 传统 AOP2、 Spri...
    luweicheng24阅读 1,386评论 0 1
  • AOP(Aspect Orient Programming),作为面向对象编程的一种补充,广泛应用于处理一些具有横...
    dolphin叔叔阅读 34,598评论 7 90
  • 因为工作需求,自己去了解一下aop并做下的记录,当然大部分都是参考他人博客以及官方文档。 目录 [关于 AOP](...
    forip阅读 2,289评论 1 20
  • 老人在树旁恬息 苍树在风中摇拽 残风在云下游走 孤云在天上看着 是什么时候我注意到了这些 还是它们早进驻了我的世界...
    衍_阅读 164评论 0 0