在spring中利用aop实现日志

首先,写一个类,继承aop的MethodInterceptor类。
public class LogIntecepter implements MethodInterceptor {

public final Object invoke(
final MethodInvocation invocation) throws Throwable {
return invokeUnderTrace(
invocation);

}

protected final Object invokeUnderTrace(
final MethodInvocation invocation) throws Throwable {

Object result = null;
KdwDebugLog debugLogger = KdwDebugLog.instanceLog();
String strClassName = "";
try {
strClassName = invocation.getThis().getClass().getName();
if (debugLogger.isInfoEnabled()) {
StringBuilder strLog = new StringBuilder(strClassName);
strLog.append("的");
strLog.append(invocation.getMethod().getName());
strLog.append("() 开始。");
debugLogger.info(strLog.toString());
}

result = invocation.proceed();

if (debugLogger.isInfoEnabled()) {
StringBuilder strLog = new StringBuilder(strClassName);
strLog.append("的");
strLog.append(invocation.getMethod().getName());
strLog.append("() 正常结束。");
debugLogger.info(strLog.toString());
}
} catch (Throwable ex) {
if (debugLogger.isErrorEnabled()) {
StringBuilder strLog = new StringBuilder(strClassName);
strLog.append("的");
strLog.append(invocation.getMethod().getName());
strLog.append("() 异常结束。");
debugLogger.error(strLog.toString());
}
if (ex instanceof CannotCreateTransactionException
|| ex instanceof TransactionSystemException) {
BLogicResult bResult = new BLogicResult();
BLogicMessages messages = new BLogicMessages();
messages.add(Globals.MESSAGE_KEY,
new BLogicMessage(
DBExceptionEnum.EXCEPTION_OTHER.getValue()));
bResult.setErrors(messages);
bResult.setResultString("fatal");
return bResult;
}
throw ex;
}

return result;
}
}


其次,配置spring的aop文件
<bean name="logIntecepter" 
scope="prototype"
class="test.LogIntecepter"/>
<aop:config>
<aop:pointcut id="logBeans" expression="bean(*BLogic)"/>
<aop:advisor
pointcut-ref="logBeans"
advice-ref="logIntecepter"/>
</aop:config>


结果:
xxxx类的方法名()开始。
xxxx类的方法名()正常结束。

MethodInvocation相关方法说明:

getArguments() -- 获得目标对象方法的入参
您可能希望更改包含在MethodInvocation类中的信息,以便在使用proceed()调用被截获的方法之前对被截获方法的参数设置新值。

通过对MethodInvocation对象调用getArguments()方法,然后在返回的数组中设置其中的一个参数对象,最初传递给被截获的方法的参数可以被更改。
例子:invocation.getArguments()[0] = new Integer(20);

proceed() -- 执行目标对象方法,并返回目标对象的返回结果

getThis() -- 获取目标对象class

getMethod() -- 获取被执行的目标对象的方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值