通过Java代理的方式:
汽车的代理,需要实现
java.lang.reflect.InvocationHandler接口
class="java" name="code">
public class CarJavaProxy implements InvocationHandler {
private Object car;
public void setCar(Object car) {
this.car = car;
}
public Object createProxy() {
Object proxy = Proxy.newProxyInstance(car.getClass().getClassLoader(), car.getClass().getInterfaces(), this);
return proxy;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(car, args);
if ("info".equalsIgnoreCase(method.getName())) {
System.out.println("Give 200 maintenance coupon via Java proxy");
}
return result;
}
}
Spring配置文件beans-java-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="carJavaProxy" class="com.john.spring.aop.CarJavaProxy">
<property name="car" ref="car" />
</bean>
</beans>
测试:
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] { "beans-java-proxy.xml" });
CarJavaProxy carProxy = (CarJavaProxy) ctx.getBean("carJavaProxy");
Vehicle vehicle = (Vehicle) carProxy.createProxy();
vehicle.info();
}
输出:
Car name: Superb, price: 220000
Give 200 maintenance coupon via Java proxy