spring aop demo
前置增强:
通过aop在目标逻辑代码前后增加其他功能,先创建某个类用于某个功能。例如创建服务员,用来模拟服务功能。
1 package AOPdemo; 2 3 public class NaiveWaiter implements Waiter { 4 5 @Override 6 public void greetTo(String name) { 7 System.out.println("greetTO "+name); 8 } 9 10 @Override 11 public void serveTo(String name) { 12 System.out.println("serveTo "+name); 13 } 14 15 }
此服务员并没有礼貌语气,通过aop添加礼貌功能,先模拟添加礼貌功能的代码
1 package AOPdemo; 2 3 import java.lang.reflect.Method; 4 5 import org.springframework.aop.MethodBeforeAdvice; 6 7 public class GreetBeforeAdvice implements MethodBeforeAdvice { 8 9 @Override 10 public void before(Method arg0, Object[] args, Object obj) throws Throwable { 11 12 String client = (String)args[0]; 13 System.out.println("welcome "+client); 14 15 } 16 17 }
此类通过实现MethodBeforeAdvice接口,重写前置增强方法来实现功能。arg0是目标方法的全名,args是目标方法入参,obj是目标实例。
1 package AOPdemo; 2 3 import org.springframework.aop.framework.ProxyFactory; 4 5 public class WaiterBerforeTest { 6 7 public static void main(String[] args) { 8 9 Waiter target = new NaiveWaiter(); 10 11 GreetBeforeAdvice advice = new GreetBeforeAdvice(); 12 13 ProxyFactory pf = new ProxyFactory(); 14 15 pf.setTarget(target); 16 17 pf.addAdvice(advice); 18 19 Waiter waiter = (Waiter)pf.getProxy(); 20 waiter.greetTo("kobe"); 21 waiter.serveTo("jordan"); 22 23 } 24 25 }
上述代码中使用ProxyFactory工厂创建代理对象,从而完成在目标方法上的增强,也可使用spring的配置方式来完成。
1 <!-- aop配置 --> 2 <bean id="target" class="AOPdemo.NaiveWaiter" ></bean> 3 <bean id="greetBeforeAdvice" class="AOPdemo.GreetBeforeAdvice"></bean> 4 5 <bean id="waiter" class="org.springframework.aop.framework.ProxyFactoryBean" 6 p:proxyInterfaces="AOPdemo.Waiter" 7 p:interceptorNames="greetBeforeAdvice" 8 p:target-ref="target" 9 />
ProxyFactoryBean在内部使用ProxyFactory来完成。ProxyFactoryBean实现了FactoryBean来创建bean。
属性介绍:proxyInterfaces,指定代理的接口
interceptorNames,使用的增强
target-ref,对目标实例进行处理
后置增强:
1 package AOPdemo; 2 3 import java.lang.reflect.Method; 4 5 import org.springframework.aop.AfterReturningAdvice; 6 7 public class GreetAfterAdvice implements AfterReturningAdvice { 8 9 @Override 10 public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable { 11 12 System.out.println("please enjoy yourself"); 13 14 } 15 16 }
1 <bean id="target" class="AOPdemo.NaiveWaiter" ></bean> 2 <bean id="greetBeforeAdvice" class="AOPdemo.GreetBeforeAdvice"></bean> 3 <bean id="greetAfterAdvice" class="AOPdemo.GreetAfterAdvice" ></bean> 4 5 <bean id="waiter" class="org.springframework.aop.framework.ProxyFactoryBean" 6 p:proxyInterfaces="AOPdemo.Waiter" 7 p:interceptorNames="greetBeforeAdvice,greetAfterAdvice" 8 p:target-ref="target" 9 />