Struts2中拦截器实现AOP的原理分析
在Struts2中,使用了拦截器来实现AOP(面向切面编程)的功能,下面来模拟实现该功能:
基于 Struts 2 拦截器实现细粒度的基于角色的存取控制:http://www.ibm.com/developerworks/cn/java/j-lo-struts2-rbac/
图片网址:http://blog.****.net/yezi77321660/article/details/3960779
接口类:Aops.java
package com.testaop; import com.testaop.imp.TestAop; public interface Aops { public void before(); public void intercept(TestAop testAop); public void after(); }
实现类:AopsImplA.java
package com.testaop.imp; import com.testaop.Aops; public class AopsImplA implements Aops{ @Override public void before() { System.out.println("执行了A的before"); } @Override public void intercept(TestAop testAop) { before(); testAop.invoke(); after(); } @Override public void after() { System.out.println("执行了A的after"); } }
AopsImplB.java
package com.testaop.imp; import com.testaop.Aops; public class AopsImplB implements Aops{ @Override public void before() { System.out.println("执行了B的before"); } @Override public void intercept(TestAop testAop) { before(); testAop.invoke(); after(); } @Override public void after() { System.out.println("执行了B的after"); } }
AopsImplC.java
package com.testaop.imp; import com.testaop.Aops; public class AopsImplC implements Aops{ @Override public void before() { System.out.println("执行了C的before"); } @Override public void intercept(TestAop testAop) { before(); testAop.invoke(); after(); } @Override public void after() { System.out.println("执行了C的after"); } }
测试类:TestAop.java,类似与ActionInvocation
package com.testaop.imp; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.testaop.Aops; public class TestAop { private Iterator<Aops> aopIterators; public void invoke(){ if(aopIterators.hasNext()){ Aops aopsImpl = (Aops)aopIterators.next(); aopsImpl.intercept(TestAop.this); }else{ System.out.println("执行了action"); } } public static void main(String[] args) { TestAop testAop = new TestAop(); List<Aops> list = new ArrayList<Aops>(); Aops aopsImplA = new AopsImplA(); Aops aopsImplB = new AopsImplB(); Aops aopsImplC = new AopsImplC(); list.add(aopsImplA); list.add(aopsImplB); list.add(aopsImplC); testAop.aopIterators = list.iterator(); testAop.invoke(); } }
执行结果:
执行了A的before
执行了B的before
执行了C的before
执行了action
执行了C的after
执行了B的after
执行了A的after
实现了AOP的功能,其中执行了action使用了before和after的通知类型
项目源码下载 testaop.rar
转载于:https://www.cnblogs.com/caroline/archive/2013/02/28/2936135.html