|
AOP(Aspect-OrientedProgramming,面向方面编程) 基于 动态代理 实现- <bean id="m" class="cn.com.xalead.spring.DynamicProxyFactory" factory-method="newInstance">
- <constructor-arg ref="me"/>
- <constructor-arg ref="servant01"/>
- <constructor-arg ref="servant02"/>
- <constructor-arg ref="servant03"/>
- <constructor-arg ref="servant04"/>
- </bean>
-
- <bean id="k" class="cn.com.xalead.spring.DynamicProxyFactory" factory-method="newInstance">
- <constructor-arg ref="king"/>
- <constructor-arg ref="servant01"/>
- <constructor-arg ref="servant02"/>
- <constructor-arg ref="servant03"/>
- <constructor-arg ref="servant04"/>
- </bean>
复制代码- public class DynamicProxyFactory implements InvocationHandler{
- private DynamicProxyFactory(){}
-
- private Servant01 servant01;
- private Servant02 servant02;
- private Servant03 servant03;
- private Servant04 servant04;
-
- private Object target;//目标对象
-
- /**
- * 创建代理类对象的方法
- * @param target 准备创建的代理类要代理的目标对象
- */
- public static Object newInstance(Object target,Servant01 servant01,Servant02 servant02,Servant03 servant03,Servant04 servant04){
- DynamicProxyFactory dp = new DynamicProxyFactory();
- dp.servant01 = servant01;
- dp.servant02 = servant02;
- dp.servant03 = servant03;
- dp.servant04 = servant04;
- dp.target = target;
- return Proxy.newProxyInstance(target.getClass().getClassLoader()
- , target.getClass().getInterfaces(),
- dp);
- }
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- servant01.makeBeds();//关注点
- servant02.dress();//关注点
- servant03.haveAMeal();//关注点
-
-
- Object o = method.invoke(target, args);//调用动态代理类代理的目标对象上的方法(真正要调用的业务方法)
-
- servant03.haveAMeal();//关注点
- servant01.makeBeds();//关注点
- servant04.undress();//关注点
- return o;
- }
- }
复制代码 |
|