发表于: 2017-11-10 20:52:02
1 780
今天完成的事。
写AOP日志
package com.xiuzhen.AOP;
import org.aopalliance.aop.Advice;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
* 检测方法执行耗时的spring切面类
* 使用@Aspect注解的类,Spring将会把它当作一个特殊的Bean(一个切面),也就是不对这个类本身进行动态代理
* Created by ${MIND-ZR} on 2017/11/10.
*/
@Aspect
@Component
public class log implements MethodInterceptor, Advice {
private static Log logger = LogFactory.getLog(log.class);
// 一分钟,即1000ms
private static final long ONE_MINUTE = 1000;
// service层的统计耗时切面,类型必须为final String类型的,注解里要使用的变量只能是静态常量类型的
public static final String POINT = "execution (* com.blinkfox.test.service.impl.*.*(..))";
/**
* 统计方法执行耗时Around环绕通知
*
* @param joinPoint
* @return
*/
@Around(POINT)
public Object timeAround(ProceedingJoinPoint joinPoint) {
// 定义返回对象、得到方法需要的参数
Object obj = null;
Object[] args = joinPoint.getArgs();
long startTime = System.currentTimeMillis();
try {
obj = joinPoint.proceed(args);
} catch (Throwable e) {
logger.error("统计某方法执行耗时环绕通知出错", e);
}
// 获取执行的方法名
long endTime = System.currentTimeMillis();
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String methodName = signature.getDeclaringTypeName() + "." + signature.getName();
// 打印耗时的信息
this.printExecTime(methodName, startTime, endTime);
return obj;
}
/**
* 打印方法执行耗时的信息,如果超过了一定的时间,才打印
*
* @param methodName
* @param startTime
* @param endTime
*/
private void printExecTime(String methodName, long startTime, long endTime) {
long diffTime = endTime - startTime;
if (diffTime > ONE_MINUTE) {
logger.info("-----" + methodName + " 方法执行耗时:" + diffTime + " ms");
}
}
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
return null;
}
}
spring文件里添加
<!--配置平台事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置通知-->
<!---->
<aop:aspectj-autoproxy />
<bean id="methodTimeAdvice" class="com.xiuzhen.AOP.log" />
<aop:config>
<!-- 用 AspectJ 的语法定义 Pointcut,这里拦截 service 包中的所有方法 -->
<aop:advisor id="methodTimeLog" advice-ref="methodTimeAdvice"
pointcut="execution(* com.xiuzhen.service.StudentServiceImpl..*.*(..))" />
</aop:config>
<bean id="yourservice" class="com.xiuzhen.service.StudentServiceImpl">
</bean>
</beans>
遇到的问题
日志打印有问题。
收获
不大,一天都在学习AOP,还没搞成功。
明天的计划。
收尾任务三
评论