Spring AOP系列之二:Java代理

通过Java代理的方式:

汽车的代理,需要实现[color=red]java.lang.reflect.InvocationHandler[/color]接口

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:


xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
default-autowire="byName">












测试:

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

你可能感兴趣的:(spring/ejb)