一、前言
通过在Spring的xml配置文件(基于注释的方式可参考其他页)对aop:config、aop:aspect、aop:pointcut、aop:before、aop:after、aop:after-returning及aop:after-throwing项分别进行配置,实现基于AOP面向切面方式记录日志功能的代码示例
二、代码示例
1.记录日志主类LogIntercept拦截器,代码如下public class LogIntercept{@b@ @b@ public void actionLog(){}@b@ @b@ @b@ public void before() {@b@ this.printLog(" @Before actionLog() 准备打印action层日志... ");@b@ }@b@ @b@ public void after() {@b@ this.printLog(" @After actionLog() action层逻辑已经执行完成 ");@b@ }@b@ @b@ public void afterReturn() throws Throwable{@b@ this.printLog(" @afterReturn actionLog() end ...... ");@b@ }@b@ @b@ public void afterThrow() {@b@ this.printLog(" @afterThrow actionLog() action层逻辑已经执行完成 ");@b@ }@b@ @b@ @b@ private void printLog(String str){@b@ System.out.println(str);@b@ }@b@ @b@}
2.spring配置文件<?xml version="1.0" encoding="UTF-8"?>@b@@b@@b@@b@@b@@b@@b@@b@@b@@b@@b@@b@@b@@b@@b@@b@@b@@b@@b@@b@@b@@b@@b@@b@
3.测试用例代码ActionLogTest,代码如下import org.junit.Test;@b@import org.springframework.beans.factory.annotation.Autowired;@b@import org.springframework.test.context.ContextConfiguration;@b@import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;@b@@b@import com.xwood.test.action.UserAction;@b@@b@@ContextConfiguration(locations={"classpath*:spring-*.xml"})@b@public class ActionLogTest extends AbstractJUnit4SpringContextTests {@b@@b@@Autowired@b@private UserAction action;@b@@b@@Test@b@ public void test() throws Exception{@b@action.login();@b@ }@b@@b@}
控制台输出日志@Before actionLog() 准备打印action层日志... @b@ 【UserAction】 用户登录 ... @b@ @After actionLog() action层逻辑已经执行完成 @b@ @afterReturn actionLog() end ......