spring aop

1 aop 术语

(1)连接点

  连接点就是考虑什么地方嵌入一个方法,比如说我现在有一个class A,A有一个方法叫login(),还有一个class B,B有一个方法叫record(),如果我们想要在A.login()方法执行前要先执行B.record()方法,那么我们直接给B.record()方法加一个Before注解就好了(下面解释),这里的在A.login方法执行前 里面的这个“执行前”就是连接点。

(2)切点

  切点就是一系列连接点的集合,我们接触过正则表达式,这里使用SqEL表达式来表达切点的集合,和正则表达式差不多,目的是选取合适的连接点。

(3)通知

  就是我们在我们想要执行的方法之前要执行的那个方法,就像例子中的B.record()

(4)切面

  切面就是通知和切点的集合,理解起来就好像一个通知的方法应用于好多连接点(切点),这两者加起来就是切面

(5)引入

  引入顾名思义是一个动作,就是将我们的切面应用到实际中,就叫做引入。

(6)目标

  目标就是被通知的对象,就好比Class A

(7)代理

  代理可以先理解为替代的意思,如果我们想执行A.login方法,但是我们又想在这个方法执行之前就去执行B.record()方法,但是我们没有更改A.login方法啊,也没有新建一个类啊,那么就用到了代理的概念,代理就好比我们想要执行A.login方法之前,Spring为我们新建了一个Class C,这个C中包含如下代码:

  public void execute(){

    B.record();

    A.Login();

  }

当然不是这么简单~但这个C就是一个代理

(8)织入

  spring 采用运行时织入,就是将切面和目标类的逻辑关系弄清楚~谁在谁前面执行,谁在后面执行,都规划好了,然后再运行程序。

2 Aop配置

(1)xml配置

  先说xml配置的话会直观一点,我们现在配置如下xml文件<?xml version="1.0" encoding="UTF-8"?>

<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.0.xsd  
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
    <context:annotation-config />
    <context:component-scan base-package="com.demo.aop"></context:component-scan>
<!-- 声明通知 -->
<bean id="B" class="com.demo.aop.B" />
<aop:config>
     <!-- 声明切点 -->
<aop:pointcut expression="execution(* com.demo.aop.A.login())" id="login"/>
<!-- 声明切面 --> <aop:aspect id="record" ref="B">
<!-- 连接点 --> <aop:before method="record" pointcut-ref="login"/>
       <aop:after method="record" pointcut-ref="login" />
</aop:aspect> </aop:config> </beans>

上面的配置就是spring aop 的xml配置方法

(2) 注解配置

package com.demo.aop;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class B {
    @Pointcut("execution(public * com.demo.aop.A.login())")
    private void prtPointCut(){}
@Before(
"prtPointCut()") public void beforePrt(){ System.out.println("before is loading..."); } @After("prtPointCut()") public void afterPrt(){ System.out.println("after is loading..."); } }

首先我们声明B为一个切面,并标注@Component注解。然后我们声明一个切点,我们给一个方法(prtPointCut())声明为切点之后,然后下面的@Before 或者 @After 注解都用的是这个方法的名字,有人也许会问到 这个prtPointCut方法中为什么没有代码,我去搜索过原因,但是可能心不诚。。没找到。。但是在这个方法中加入代码是不会执行的。具体原因我也想求教一下~这样一个简单的aop配置就结束了。

posted @ 2018-01-25 13:16  砂糖橘子君  阅读(165)  评论(0编辑  收藏  举报