AOP常用的几种增强方式,各自的特点

本文详细介绍了Spring AOP的五种增强类型:前置增强、后置增强、环绕增强、异常抛出增强和引介增强。通过实例展示了如何使用接口、XML配置和注解方式实现这五种增强,包括它们在目标方法执行前后的具体应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringAOP的5种增强类型应用讲解
一.前言
spring框架中为我们提供的增强包括针对切面的增强和针对切入点的增强,对一个方法的增强底层使用的是动态代理,所以在学习springAop增强之前大家有必要先了解一下动态代理相关内容;
本文分别采用继承接口和使用配置文件来实现增强。

二.springAOP自带的增强类型
按照增强在目标类方法中的连接点位置,可以分为5种:
1.前置增强:org.springframework.aop.BeforeAdvice是前置增强顶层接口,因为Spring只持方法的增强,其子接口MethodBeforeAdvice是目前可用的前置增强。表示在目标方法执行前实施增强。

2.后置增强:org.springframework.aop.AfterReturningAdvice是目前可用的后置增强,表示在目标方法执行后实施增强。

3.环绕增强:org.aopalliance.intercept.MethodInterceptor代表了环绕增强,表示在目标方法执行前后实施增强。直接使用了AOP联盟定义的接口。

4.异常抛出增强:org.springframework.aop.ThrowsAdvice代表了异常抛出增强,表示在目标方法抛出异常后实施增强。

5.引介增强:org.springframework.aop.IntroductionInterceptor代表引介增强,表示在目标类中添加一些新的方法和属性。

三.五种增强的具体使用方法

一,前置增强
1,我们先不用配置文件,先使用原始的方法–继承底层接口的形式来实现增强。配置文件或者注解的底层也是使用这些接口来生成代理的。
首先,创建maven工程,利用pom文件自动导入所需的包。
然后,编写目标类和增强类。
1实现接口方式实现前置增强

package com.jimmy.mvn.a.BeforeAdvice;

/**
 * 目标类(被增强类),say方法将被增强,其中say方法执行前后都可以是切入点(point-cut)
 */
public class Target {
    public void say() {
        System.out.println("我需要被增强!");
    }
}


package com.jimmy.mvn.a.BeforeAdvice;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;

/**
 * 增强类,用于在切入点处进行增强
 * 
 * 该类实现了MethodBeforeAdvice接口,并实现了唯一的before()方法。
 * 
 */
public class Advice implements MethodBeforeAdvice{

    /**
     * method是目标类的方法
     * args是目标类方法的入参
     * target是目标类实例
     * 
     * before()方法会在目标类方法调用前执行。
     */
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("我是前置增强,很高兴为你服务!");
    }   
}


//测试方法
package com.jimmy.mvn.SpringAdvice;

import org.springframework.aop.framework.ProxyFactory;

import com.jimmy.mvn.a.BeforeAdvice.Advice;
import com.jimmy.mvn.a.BeforeAdvice.Target;

public class BeforeAdviceTest {
    public static void main(String[] args) {

        Target target = new Target();  // 目标类对象
        Advice advice = new Advice();  // 增强类对象

        ProxyFactory pf = new ProxyFactory(); // Spring提供的代理工厂
        pf.setTarget(target);  // 设置代理目标
        pf.addAdvice(advice);  // 为代理目标添加增强

        Target target2 = (Target) pf.getProxy(); // 生成代理实例
        target2.say();  // 代理对象再调用say()方法就能产生前置增强
    }
}


2使用xml配置文件的方式实现前置增强
首先,还是先创建maven工程,自动导入需要的包。
然后,创建目标类和增强类。

package com.jimmy.mvn.a.BeforeAdviceXML;

/**
 * 目标类。同上,很普通的一个类,实际开发中往往是一个业务类 
 */
public class Target {
    public void say() {
        System.out.println("我需要被增强!");
    }
}

package com.jimmy.mvn.a.BeforeAdviceXML;

/**
 * 增强类,该类不再继承任何接口,就是个普通的POJO类
 * 
 * 从外观上看,根本看不出来这个类要干嘛 
 */
public class Advice {   
    public void beforeAdvice() {
        System.out.println("我是前置增强,很高兴为你服务!");
    }
}


然后再针对切入点编写配置文件

<?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:aop="http://www.springframework.org/schema/aop" 
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

    <bean id="target" class="com.jimmy.mvn.a.BeforeAdviceXML.Target"></bean>
    <bean id="advice" class="com.jimmy.mvn.a.BeforeAdviceXML.Advice"></bean>

    <aop:config>
        <aop:aspect ref="advice">           
            <aop:before method="beforeAdvice" pointcut="execution(* com.jimmy.mvn.a.BeforeAdviceXML.*.*(..))"/>         
        </aop:aspect>
    </aop:config>     
</beans>


解读上面的配置文件:
1,定义2个bean,target是增强后的bean,而advice是为了在文件中被切面引用。
2,aop:config,AOP设置的最外层元素,一个文件可以有多个aop:config,不同的aop:config可以采用不同的代理技术。
3,aop:aspect,改元素定义一个切面,其ref属性用来引用增强类的bean。
4,aop:before,定义一个前置增强,method属性是增强类bean中的方法名;pointcut属性是一个“切点表达式”,该表达式用于匹配“切入点”,即需要被增强的bean的方法。
编写测试类

package com.jimmy.mvn.SpringAdvice;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.jimmy.mvn.a.BeforeAdviceXML.Target;

public class BeforeAdviceXMLTest {
    public static void main(String[] args) {

        String path = "com/jimmy/mvn/a/BeforeAdviceXML/smart-context.xml";
        ApplicationContext app1 = new ClassPathXmlApplicationContext(path);
        Target target = (Target) app1.getBean("target");
        target.say();
    }

注:配置文件配置AOP时,有很多种写法,还可以将“切点表达式”单独命名,如下:

<bean id="target" class="com.jimmy.mvn.a.BeforeAdviceXML.Target"></bean>
<bean id="advice" class="com.jimmy.mvn.a.BeforeAdviceXML.Advice"></bean>

<aop:config>
    <aop:aspect ref="advice">
        <aop:pointcut id="pointcut" expression="execution(* com.jimmy.mvn.a.BeforeAdviceXML.*.*(..))"/>
        <aop:before method="beforeAdvice" pointcut-ref="pointcut"/>
    </aop:aspect>
</aop:config>  

当然,还可以将aop:pointcut提取出来,单独写,可以供很多切面aop:aspect引用:

 <bean id="target" class="com.jimmy.mvn.a.BeforeAdviceXML.Target"></bean>
    <bean id="advice" class="com.jimmy.mvn.a.BeforeAdviceXML.Advice"></bean>

    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* com.jimmy.mvn.a.BeforeAdviceXML.*.*(..))"/>
<--配置两个相同的beforeAdvice就可以在执行这个方法之前执行两次增强-->
        <aop:aspect ref="advice">
            <aop:before method="beforeAdvice" pointcut-ref="pointcut"/>
        </aop:aspect>
        <aop:aspect ref="advice">
            <aop:before method="beforeAdvice" pointcut-ref="pointcut"/>
        </aop:aspect>
    </aop:config>   

3基于Annotation注解方式进行增强
首先,创建maven工程,自动导入所需要的包
然后,编写目标类和增强类。

package com.jimmy.mvn.a.BeforeAdviceAnnotation;
/**
 * 目标类。同上,很普通的一个类,实际开发中往往是一个业务类 
 */
public class Target {
    public void say() {
        System.out.println("我还要被增强!");
    }
}

package com.jimmy.mvn.a.BeforeAdviceAnnotation;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

/**
 * 增强类,使用注解开发,该类同样不再继承任何接口
 * 
 * @Aspect用于将类标识为一个切面
 * @Before("execution(...)")用于将方法标识为增强方法,"切入点表达式"用于定位被切入方法。
 */
@Aspect
public class Advice {   

    @Before("execution(* *..Target.*(..))")
    public void beforeAdvice() {
        System.out.println("我是前置增强,很高兴为你服务!");
    }
}


再然后,我们仍然需要配置一点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:aop="http://www.springframework.org/schema/aop" 
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

    <aop:aspectj-autoproxy/>
    <bean id="target" class="com.jimmy.mvn.a.BeforeAdviceAnnotation.Target"></bean>
    <bean id="advice" class="com.jimmy.mvn.a.BeforeAdviceAnnotation.Advice"></bean>       
</beans>

解读上述配置文件,文件中只有短短的3行配置。
1,aop:aspectj-autoproxy自动为Spring容器中那些匹配@Aspect切面的bean创建代理,完成切面织入。
2,两个bean,其中target供测试时getBean方法调用;advice可以没有id,其为自动创建代理时使用。
最后,编写测试类

package com.jimmy.mvn.SpringAdvice;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.jimmy.mvn.a.BeforeAdviceAnnotation.Target;

public class BeforeAdviceAnnotationTest1 {
    public static void main(String[] args) {        
        String path = "com/jimmy/mvn/a/BeforeAdviceAnnotation/smart-context.xml";
        ApplicationContext app1 = new ClassPathXmlApplicationContext(path);
        Target target = (Target) app1.getBean("target");
        target.say();
    }
}

二,后置增强
跟前置增强的使用一样一样的。

三,环绕增强
1,基于MethodIntercepter接口方式实现环绕增强
首先,创建maven工程,自动导入jar包。
然后,创建目标类和增强类。

package com.jimmy.mvn.b.AroundAdvice;
/**
 * 目标类,普通POJO类,其say方法被增强。
 */
public class Target {
    public void say(){
        System.out.println("我需要前后都增强!");
    }
}

package com.jimmy.mvn.b.AroundAdvice;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

/**
 * 增强类实现了MethodInterceptor接口,并实现了其中的invoke方法
 */
public class AroundAdvice implements MethodInterceptor{

    /**
     * 该方法截获目标类方法的执行,并在前后加上横断逻辑
     */
    public Object invoke(MethodInvocation invocation) throws Throwable {

        System.out.println("我是前置增强,很高兴为你服务!"); // 前置增强
        Object obj = invocation.proceed(); // 通过反射机制调用目标方法
        System.out.println("我是后置增强,很高兴为你服务!"); // 后置增强
        return obj;
    }
}


最后,编写测试类,该测试类跟前置增强时用的一样。

package com.jimmy.mvn.SpringAdvice;

import org.springframework.aop.framework.ProxyFactory;

import com.jimmy.mvn.b.AroundAdvice.AroundAdvice;
import com.jimmy.mvn.b.AroundAdvice.Target;

public class AroundAdviceTest {
    public static void main(String[] args) {
        Target target = new Target();
        AroundAdvice advice = new AroundAdvice();

        ProxyFactory pf = new ProxyFactory();
        pf.setTarget(target);
        pf.addAdvice(advice);

        Target target2 = (Target) pf.getProxy();
        target2.say();
    }
}


2.基于xml方式实现spring的环绕增强
首先,创建maven工程,自动导入jar包。
然后,创建目标类和增强类。

package com.jimmy.mvn.b.AroundAdviceXML;
/**
 * 目标类,跟上面是一样一样的。
 */
public class Target {
    public void say() {
        System.out.println("我还要前后增强!");
    }
}

package com.jimmy.mvn.b.AroundAdviceXML;

import org.aspectj.lang.ProceedingJoinPoint;

/**
 * 增强类,普通POJO类,不再继承任何接口。
 * 自定义环绕增强方法,由于是要在切入点前后横插入逻辑,所以将ProceedingJoinPoint接口对象pjp作为方法的入参。
 * pjp.proceed()方法通过反射机制调用目标方法。
 * 在pjp.proceed()前后加上横断逻辑。
 */
public class AroundAdvice {

    public void myAroundAdvice(ProceedingJoinPoint pjp) throws Throwable{
        System.out.println("我是前置增强,很高兴为你服务!");
        pjp.proceed();
        System.out.println("我是后置增强,很高兴为你服务!");
    }
}


再然后,编写配置文件,smart-context.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:aop="http://www.springframework.org/schema/aop" 
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

    <bean id="target" class="com.jimmy.mvn.b.AroundAdviceXML.Target"></bean>
    <bean id="advice" class="com.jimmy.mvn.b.AroundAdviceXML.AroundAdvice"></bean>

    <aop:config>
        <aop:aspect ref="advice">           
            <aop:around method="myAroundAdvice" pointcut="execution(* *..Target.*(..))"/>           
        </aop:aspect>
    </aop:config>     
</beans>


我们看到,配置文件跟前置增强的差别不大,无非是把aop:before换成了aop:around。

最后,编写测试类。

package com.jimmy.mvn.SpringAdvice;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.jimmy.mvn.b.AroundAdviceXML.Target;

public class AroundAdviceXMLTest {
    public static void main(String[] args) {
        String path = "com/jimmy/mvn/b/AroundAdviceXML/smart-context.xml";
        ApplicationContext app1 = new ClassPathXmlApplicationContext(path);
        Target target = (Target) app1.getBean("target");
        target.say();
    }
}

3.基于Annotation方式实现环绕增强
首先,创建maven工程,自动导入jar包。
然后,创建目标类和增强类。

package com.jimmy.mvn.b.AroundAdviceAnnotation;

public class Target {
    public void say() {
        System.out.println("我还要前后增强!");
    }
}

package com.jimmy.mvn.b.AroundAdviceAnnotation;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class AroundAdvice {
    @Around(value = "execution(* *..Target.*(..))")
    public void myAroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("我是前置增强,很高兴为你服务!");
        pjp.proceed();
        System.out.println("我是后置增强,很高兴为你服务!");
    }
}


再然后,编写配置文件,smart-context.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:aop="http://www.springframework.org/schema/aop" 
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

    <aop:aspectj-autoproxy/>
    <bean id="target" class="com.jimmy.mvn.b.AroundAdviceAnnotation.Target"></bean>
    <bean id="advice" class="com.jimmy.mvn.b.AroundAdviceAnnotation.AroundAdvice"></bean>  
</beans>


最后,编写测试代码

package com.jimmy.mvn.SpringAdvice;

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

import com.jimmy.mvn.b.AroundAdviceAnnotation.Target;

public class AroundAdviceAnnotationTest {
    public static void main(String[] args) {
        String path = "com/jimmy/mvn/b/AroundAdviceAnnotation/smart-context.xml";
        ApplicationContext app1 = new ClassPathXmlApplicationContext(path);
        Target target = (Target) app1.getBean("target");
        target.say();
    }
}

Spring-AOP的四种增强方式(前置增强、后置增强、异常增强、环绕增强)

1. 前置增强,在核心功能之前执行的额外功能

 

 2. 后置增强,在核心功能之后执行的额外功能

 

 3.异常增强,在核心功能发生异常时执行的额外功能,先捕获,后抛出

 

4. 环绕增强,在核心功能之前以及之后执行的额外功能

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值