Spring的aop简单示例
我们有几个平台都用spring框架,里面跑有spring-quartz定时任务。现在做系统优化,用ThreadLocal管理mysql或者redis等连接,这些连接在http请求的filer结尾关闭即可。但是对于quartz,而且是spring管理的quartz,需要使用aop的方式切入quartz执行的结尾,统一关闭,防止其他工程师编码时候忘记了。
实现aop的方式很多,我还是比较喜欢完全替换模式的拦截器org.aopalliance.intercept.MethodInterceptor,依赖包文件aopalliance-1.0.jar
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="quartzAspectBean" class="com.qingmayun.common.quartz.QuartzAdvice"/>
<aop:config proxy-target-class="true">
<aop:advisor id="quartzAspect" advice-ref="quartzAspectBean" pointcut="execution(* com.okboo.openweb.quartz.*Job.execute(..))"/>
</aop:config>
其他quartz配置省略
</beans>
QuartzAdvice.java
public class QuartzAdvice implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
try {
return invocation.proceed();
}finally
{
// System.out.println("============sheep==============fk");
JedisManager.closeAll();
}
}
}
完事,注意配置文件的pointcut第一个*和com之间有一个空格。