首先,写一个类,继承aop的MethodInterceptor类。
其次,配置spring的aop文件
结果:
xxxx类的方法名()开始。
xxxx类的方法名()正常结束。
MethodInvocation相关方法说明:
getArguments() -- 获得目标对象方法的入参
您可能希望更改包含在MethodInvocation类中的信息,以便在使用proceed()调用被截获的方法之前对被截获方法的参数设置新值。
通过对MethodInvocation对象调用getArguments()方法,然后在返回的数组中设置其中的一个参数对象,最初传递给被截获的方法的参数可以被更改。
例子:invocation.getArguments()[0] = new Integer(20);
proceed() -- 执行目标对象方法,并返回目标对象的返回结果
getThis() -- 获取目标对象class
getMethod() -- 获取被执行的目标对象的方法
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() -- 获取被执行的目标对象的方法