Spring基础(16)——AOP——AroundAdvice

本文介绍Spring AOP中环绕通知的概念与应用,通过具体示例展示了如何使用GreetingAroundAdvice实现方法调用前后的通知功能,并控制目标方法的执行流程。

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

Around Advice是环绕通知,是最常用的通知类型。前置通知和后置通知分别在目标类方法的前后织入通知,但是如果同时使用这两种类型的通知,使用环绕通知同样可以实现效果。

MethodInterceor

能够控制目标方法是否真的被调用。通过调用MethodInvocation.proceed()方法来调用目标方法。这一点不同于MethodBeforeAdvice,目标方法总是被调用,除非抛异常。

能够控制返回的对象,可以返回一个与MethodInvocation.proceed()方法返回的对象完全不同的对象。使用AfterReturningAdvice可以返回对象,但是不能返回一个不同的对象。相比,更加灵活。

package test.advice;

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

public class GreetingAroundAdvice implements MethodInterceptor {

	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		// TODO Auto-generated method stub
		
		Object args[] = invocation.getArguments();
		String customName = (String) args[0];
		System.out.println("欢迎:" + customName);
		
		Object obj = invocation.proceed();
		
		System.out.println("结束,再见:" + customName);
		return obj;
	}

}
<?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:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans.xsd 
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context.xsd 
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">


	<bean id="greetingBeforeAdvice"
		class="test.advice.GreetingBeforeAdvice">
	</bean>
	<bean id="greetingAroundAdvice"
		class="test.advice.GreetingAroundAdvice">
	</bean>
	<bean id="reception"
		class="org.springframework.aop.framework.ProxyFactoryBean">
		<property name="proxyInterfaces"
			value="test.advice.Reception"></property>

		<property name="interceptorNames"
			>
			<list>
				<!-- <value>greetingAfterAdvice</value>
				<value>greetingBeforeAdvice</value> -->
				<value>greetingAroundAdvice</value>
			</list>
		</property>
		<property name="target" ref="target"></property>
	</bean>
	<bean id="target" class="test.advice.ConcreteReception"></bean>
	<bean id="greetingAfterAdvice"
		class="test.advice.GreetingAfterAdvice">
	</bean>
</beans>
欢迎:Test
我正在服务客户:Test
结束,再见:Test



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值