通过实现
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的代理生成: