需求:在所有打印SQL语句前,加上SQL所在的类名及方法名。
解决方法:使用spring面向切面编程。
具体代码:
package com.hys.qiantai.struts.action.liveservice;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;
/**
*/
public class LogDaoMethodPointcut implements MethodInterceptor {
private static final Logger logger = Logger.getLogger(LogDaoMethodPointcut.class);
@Override
public Object invoke(MethodInvocation arg0) throws Throwable {
System.out.println("Before: class: {} " + arg0.getThis().getClass());
System.out.println("Method name: {} " + arg0.getMethod().getName());
logger.info("Before: class: {} " + arg0.getThis().getClass());
logger.info("Method name: {} " + arg0.getMethod().getName());
return arg0.proceed();
}
}
<!-- 方法拦截器 MethodInterceptor applicationContext_transaction.xml -->
<bean id="logDaoMethodPointcut" class="com.hys.qiantai.struts.action.liveservice.LogDaoMethodPointcut"></bean>
<aop:config proxy-target-class="true">
<aop:pointcut id="daoMethodPointcut" expression="execution(* com.hys.exam.dao.local.jdbc.*.*(..))"/>
<aop:advisor advice-ref="logDaoMethodPointcut" pointcut-ref="daoMethodPointcut" />
</aop:config>