通過Spring AOP 攔截 SQL
sql 的重要性,開發人員都很清除,並不是所有人和時刻都記得log sql ,為了不侵入原來已經寫好的程式碼,亦為了將來可以方便移走log,採用spring 的AOP 來記錄log 是件很有意義的事情。配置如下
<bean id="theTracingBeforeAdvice" class="your.com.TracingBeforeAdvice"/>
<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="proxyTargetClass">
<value>true</value>
</property>
<property name="interceptorNames">
<list>
<value>theTracingBeforeAdvice</value>
</list>
</property>
<property name="beanNames">
<list>
<value>jdbcTemplate</value>
</list>
</property>
</bean>
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/mytest?useUnicode=true&characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="123456" />
<property name="maxActive" value="100" />
<property name="maxIdle" value="30" />
<property name="maxWait" value="1000" />
<property name="defaultAutoCommit" value="true" />
<property name="removeAbandoned" value="true" />
<property name="removeAbandonedTimeout" value="60" />
</bean>
有一點是很重要,spring 自動代理預設為介面,如果要代理類,需要在屬性中指出,如上面的粗體
實現類
public class TracingBeforeAdvice implements MethodBeforeAdvice {
private Logger logger = Logger.getLogger(TracingBeforeAdvice.class);
public void before(Method m, Object[] args, Object target) throws Throwable {
if (args != null) {
logger.warn( target.getClass().getName() + "." + m.getName() );
logger.warn(target.getClass().getName());
if (args.length>0)
{
for(int i=0;i<args.length;i++)
logger.warn( args[i]);
}
}
}
}