Spring -- AOP

概念简介

    AOP(Aspect-Oriented Programming, 面向切面编程):是一种新的方法论,是对传统 OOP(面向对象编程))的补充。


其实只要理解了Java的动态代理,就基本就理解AOP了,都是用来实现同一个目标的。

在知乎上有篇回答解释的很清楚:

地址:https://www.zhihu.com/question/24863332


总而言之:在运行时动态地将代码切入到类的指定方法、指定位置上的编程思想就是面向切面编程。


AOP术语

 

切面(Aspect):类似于OOP中的Class,一个Aspect存放一个系统功能的所有逻辑;在ApplicationContext中aop:aspect来配置;

 

连接点(Joinpoint):程序执行过程中的某一事件,如方法被调用时、抛出异常时;

 

切入点(Pointcut):它是一个表达式,用于确定哪些类的哪些函数需要插入横切逻辑;它只精确到函数,究竟要在函数执行的哪个阶段插入横切逻辑,这就由通知的类型决定;

 

通知(Advice 也称为增强处理):具体的横切逻辑;Spring中有四种Advice:  

前置通知(Before Advice)

后置通知(After Advice)

返回通知(After Return Advice)

环绕通知(Around Advice)

抛出异常后通知(After Throwing Advice)

 

作者:大闲人柴毛毛

链接:https://www.zhihu.com/question/24863332/answer/253016908

来源:知乎


Spring的AOP支持

    Spring中的AOP代理有IoC容器负责生成、管理,其依赖关系也由IoC容器负责管理。Spring关于AOP支持有两种实现方法,一种是Java的动态代理,一种是Cglib。默认是使用动态代理的,但这种方式需要有接口,略显麻烦,这里就用后者吧。

    

首先要引入SpringAOP的包,这里是用maven构建的项目,直接上maven依赖吧:

    

    <dependency>

        <groupId>org.springframework</groupId>

        <artifactId>spring-aop</artifactId>

        <version>4.3.11.RELEASE</version>

    </dependency>

 

Spring核心配置文件中的配置:

1.添加aop schema文件:


2.为了在应用中使用@AspectJ支持,Spring需要添加三个库:

aspectjweaver.jar

aspectjrt.jar

aopalliance.jar


Maven依赖:

<dependency>
    <groupId>aopalliance</groupId>
    <artifactId>aopalliance</artifactId>
    <version>1.0</version>
</dependency>
<dependency>
    <groupId>aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.5.3</version>
</dependency>
<dependency>
    <groupId>aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.2</version>
</dependency>    

完成上述步骤之后,项目可以用AspectJ来实现AOP了。


配置文件:


aop:pointcut:声明一个切点,切点可以理解为一个条件,切点决定了能够定位到哪些连接点上。连接点可以认为是某个方法,一个切点下可以有多个连接点。

aspect:代理,ref的值是一个类,这个可是代理类,类中可以定义代理的要实现的功能。

aop:before:前置通知,其实就是个方法,在连接点执行之前执行。

aop:after:后置通知,连接点执行之后执行。

aop:after-throwing:异常通知,在连接点出现异常后执行。

 

各种通知都有method属性,表示要执行的方法,方法需要在代理类中定义,

pointcut-ref表示属于哪个切点,图中很显然就是myPointCut。



关于切点表达式的补充说明:

最典型的切入点表达式是根据方法的签名来匹配各种方法:

execution (* com.easytop.spring.ArithmeticCalculator.*(..) ):

匹配 ArithmeticCalculator 中声明的所有方法,第一个 * 代表任意修饰符及任意返回值. 第二个 * 代表任意方法. .. 匹配任意数量的参数. 若目标类与接口与该切面在同一个包中, 可以省略包名.

 

execution (public * ArithmeticCalculator.*(..)): 匹配 ArithmeticCalculator 接口的所有公有方法.

execution (public double ArithmeticCalculator.*(..)): 匹配 ArithmeticCalculator 中返回 double 类型数值的方法

execution (public double ArithmeticCalculator.*(double, ..)): 匹配第一个参数为 double 类型的方法,.. 匹配任意数量任意类型的参数

execution (public double ArithmeticCalculator.*(double, double)): 匹配参数类型为 double, double 类型的方法.



以租房为例,写个小例子:

/**
 * 房东抽象接口
 * @author Administrator
 *
 */
public interface LandLord {

        /**
         * 出租房子
         */
        public void rentHouse();
        
        public void rentHouse(String tips);
}

 

房东实现类:

import org.springframework.stereotype.Component;

/**
 * 房东接口实现类
 * @author Administrator
 *
 */
@Component
public class SzLandLord implements LandLord{

        public void rentHouse() {
                System.out.println("老子现在把房租给你-------->");
        }
        
        public void rentHouse(String tips){
                System.out.println("老子现在把房子租给你,顺便加个小提醒:" + tips);
        }
}

代理

import java.text.SimpleDateFormat;
import java.util.Date;

import org.aspectj.lang.JoinPoint;
import org.springframework.stereotype.Component;

/**
 * 代理类,定义每个连接点的通知
 * @author Administrator
 *
 */

@Component
public class MyMessage {

        public void beforeRent() {
                System.out.println("前置通知:帮租客打扫卫生-->\n");
        }

        public void afterRent() {
                System.out.println("\n后置通知:向租客收押金和房租-->");
        }
        
        /**
              JoinPoint是org.aspectj.lang包下的一个类,
              详情:http://blog.sina.com.cn/s/blog_b8ba98b50102wn8h.html
        */
        public void exception(JoinPoint joinPoint){
                System.out.println("\n租房过程出现异常!");
                System.out.println("异常方法:" + joinPoint.getSignature().getName());
                System.out.println("异常发生时间:" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));        
        }
}

测试类

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
        
        // Spring容器对象
        static ApplicationContext context;
        static{
                
                //  初始化容器对象 
                context = new ClassPathXmlApplicationContext("classpath:/lesson03/aop/spring.xml");
        }
        
        public static void main(String[] args) {
                
                // 获取房东实例
                LandLord lord = (LandLord)context.getBean("szLandLord");
                
                lord.rentHouse("这个房子闹鬼");
        }
}


运行结果:



现在来抛个异常:



运行结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值