通過實現
org.aopalliance.intercept.MethodInterceptor
接口來實現環繞通知:
Spring配置文件beans-around-proxy.xml:
測試:
輸出:
Skoda 4S shop
Car name: Superb, price: 220000
Give 200 maintenance coupon via around proxy
調試程序,vehicle使用JDK的代理生成:
public class CarAroundProxy implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable { System.out.println("Skoda 4S shop"); Object result = invocation.proceed(); System.out.println("Give 200 maintenance coupon via around proxy"); return result; } }
Spring配置文件beans-around-proxy.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" default-autowire="byName"> <bean id="car" class="com.john.spring.aop.Car"> <property name="name" value="Superb" /> <property name="price" value="220000" /> </bean> <bean id="carAroundProxy" class="com.john.spring.aop.CarAroundProxy" /> <!-- 通過ProxyFactoryBean來生成實現指定接口,攔截指定對象方法的代理類 --> <bean id="proxyBean" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces"><!-- 代理需實現的接口 --> <value>com.john.spring.aop.Vehicle</value> </property> <property name="interceptorNames"><!-- 攔截器名稱列表 --> <list> <value>carAroundProxy</value> </list> </property> <property name="target"><!-- 目標對象 --> <ref bean="car" /> </property> </bean> </beans>
測試:
public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] { "beans-around-proxy.xml" }); Vehicle vehicle = (Vehicle) ctx.getBean("proxyBean"); vehicle.info(); }
輸出:
Skoda 4S shop
Car name: Superb, price: 220000
Give 200 maintenance coupon via around proxy
調試程序,vehicle使用JDK的代理生成:

更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
