1.采用Interception Around通知的形式实现
Interception Around通知会在Join Point的前后执行,实现Interception Around通知的类需要实现接口MethodInterceptor。其实现思路是:
1)首先实现接口MethodInterceptor,在Invoke()方法里编写负责输出日志信息的代码,具体业务逻辑还使用前面的接口TimeBookInterface和它的实现类TimeBook
2)然后在Spring的配置文档中定义PointCut
3)最后编写测试程序,执行,查看输出
1)编写负责输出日志信息的类LogAround
//****LogAround.java**** package com.gc.action import org.aopalliance.interceptor.MethodInvocation; import org.aopalliance.interceptor.MethodInterceptor; import org.apache.log4j.Level; import org.apache.log4j.Logger; //Interception Around通知会在Join Point的前后执行 public class LogAround implements MethodIntercetor{ private Logger logger = Logger.getLogger(this.getClass().getName()); //负责输出日志信息的代码 public Object invoke(MethodInvocation mi) throw Throwabel{ logger.log(Level.INFO,mi.getArguments()[0]+"开始审核数据..."); try{ Object result = mi.proceed(); return result; } finally{ logger.log(Level.INFO,mi.getArguments()[0]+"审核数据结束...") } } }
参数MethodInvocation:通过它可以获得方法的名称,程序传入的参数Object[]等
proceed方法,通过它即可执行被调用的方法
return result,返回值为被调用方法的返回值
com.gc.impl包中的接口和 com.gc.action包中的类
//*****TimeBookInterface.java**** package com.gc.impl; import org.apache.log4j.Level; public interface TimeBookInterface{ public void doAuding(String name); } //*****TimeBook.java******* package com.gc.action; import com.gc.impl.TimeBookInterface; public class TimeBook implements TimeBookInterface{ public void doAuditing(String name){ .... } }
2)定义Spring的配置文档config.xml
<!xml version="1.0" encoding = "UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd" > <beans> <bean id="HelloWorld" class = "com.gc.action.HelloWorld" depends-on="date"> <property name = "msg"> <value>HelloWorld</value> </property> <property name = "date"> <ref bean = "date"/> </property> </bean> <bean id="date" class="java.util.Date"/> <bean id="log" class="com.gc.action.LogAround"/> <bean id="timeBook" class="com.gc.action.TimeBook"/> <bean id="logProxy" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces"> <value>com.gc.impl.TimeBookInterface</value> </property> <property name="target"> <ref Bean="timeBook"/> </proterty> <property name="interceportNames"> <list> <value>log</value> </list> </property> </bean> </beans>
id为log的Bean,负责输出日志信息;
id为timeBook的Bean,负责具体的业务逻辑考勤审核
id为logProxy的Bean,使用Spring提供的ProxyFactoryBean来实现代理,在该Bean里定义相关的属性,包括要代理的接口,目标类急要使用的Interceptor。
3)测试代码
1 //******TestHelloWorld********* 2 3 package com.gc.test; 4 5 import com.gc.action.TimeBook; 6 import com.gc.aciton.TimeBookProxy; 7 import com.gc.impl.TimeBookInterface; 8 public class TestHelloWorld{ 9 public static void main(String[] args){ 10 ApplicationContext actx = new FileSystemXmlApplicationContext("config.xml"); 11 TimeBookInterface timeBookProxy = (TimeBookInterface)actx.getBean("logProxy"); 12 timeBookProxy.doAuditing("张三"); 13 } 14 15 }