aop动态日志居然不执行,查出原因,在此记录!
代码如下。。
<!-- 定义日志输出切面-->
<bean id="showLog" class="com.xmsmartcity.maintain.common.ShowLogAspect" />
<aop:config>
<aop:aspect id="showLogAspect" ref="showLog" >
<aop:pointcut expression="execution(* com.xmsmartcity.maintain.controller.mobile.*.*(..))" id="logPointcut"/>
<aop:after-returning method="doAfter" returning="returnValue" pointcut-ref="logPointcut" />
</aop:aspect>
</aop:config>
public class ShowLogAspect{
/**
* 日志输出
* @param point
* @throws ClassNotFoundException
* @throws NotFoundException
*/
public void doAfter(JoinPoint point,Object returnValue) throws ClassNotFoundException, NotFoundException{
Object target = point.getTarget();
Logger logger = Logger.getLogger(target.getClass());
logger.debug("method: "+point.getSignature().getDeclaringTypeName()+"." + point.getSignature().getName());
String classType = point.getTarget().getClass().getName();
Class<?> clazz = Class.forName(classType);
String clazzName = clazz.getName();
String methodName = point.getSignature().getName();
String[] paramNames = getFieldsName(this.getClass(), clazzName, methodName);
Object[] objs = point.getArgs();
for(int i =0;i<objs.length;i++){
if(objs[i] != null){
if(objs[i].getClass().getAnnotation(Entity.class) != null){
logger.debug("param: "+paramNames[i]+"="+JSONObject.fromObject(objs[i]).toString());
}else{
logger.debug("param: "+paramNames[i]+"="+objs[i]);
}
}
}
logger.debug("return value: "+returnValue);
}
/**
* 得到方法参数的名称
* @param cls
* @param clazzName
* @param methodName
* @return
* @throws NotFoundException
*/
private static String[] getFieldsName(Class<?> cls, String clazzName, String methodName) throws NotFoundException{
ClassPool pool = ClassPool.getDefault();
ClassClassPath classPath = new ClassClassPath(cls);
pool.insertClassPath(classPath);
CtClass cc = pool.get(clazzName);
CtMethod cm = cc.getDeclaredMethod(methodName);
MethodInfo methodInfo = cm.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
if (attr == null) {
// exception
}
String[] paramNames = new String[cm.getParameterTypes().length];
int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
for (int i = 0; i < paramNames.length; i++){
paramNames[i] = attr.variableName(i + pos); //paramNames即参数名
}
return paramNames;
}
public void LogBefore(){
System.out.println("=============================----------------->Log before method");
}
}
发现原因是
<!-- 扫描controller下包 -->
<context:component-scan base-package="com.xmsmartcity.maintain.controller" />
扫描写在了父容器中,所以不执行aop方法。。