直接上代码,有不足之处希望大家指出来
首先创建一个Action类
类 Caction
package advice;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @description 类的方法描述注解
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface CAction {
/**
* 方法描述
* @return
*/
public String description() default "no description";
}
类 LogAspect
package advice;
import javax.annotation.Resource;
import org.aspectj.lang.annotation.Aspect;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import po.ELogType;
import po.SysLog;
import po.SysOperator;
import biz.ISysLogBiz;
import com.opensymphony.xwork2.ActionContext;
/**
* 系统操作日志切面
*
*/
@Aspect
public class LogAspect {
@Resource(name="sysLogBiz")
private ISysLogBiz sysLogBiz;
private Log logger = LogFactory.getLog(LogAspect.class);
public Object doSystemLog(ProceedingJoinPoint point) throws Throwable {
String methodName = point.getSignature().getName();
// 目标方法不为空
if (StringUtils.isNotEmpty(methodName)) {
// set与get方法除外
if (!(methodName.startsWith("set") || methodName.startsWith("get"))) {
Class targetClass = point.getTarget().getClass();
Method method = targetClass.getMethod(methodName);
if (method != null) {
boolean hasAnnotation = method.isAnnotationPresent(CAction.class);
if (hasAnnotation) {
CAction annotation = method.getAnnotation(CAction.class);
String methodDescp = annotation.description();
if (logger.isDebugEnabled()) {
logger.debug("CAction method:" + method.getName() + " Description:" + methodDescp);
}
//取到当前的操作用户
SysOperator appUser=(SysOperator)ActionContext.getContext().getSession().get("Login_user");
if(appUser!=null){
SysLog sysLog=new SysLog();
try{
sysLog.setCd(new Timestamp(System.currentTimeMillis()));
sysLog.setOperId(appUser.getId());;
sysLog.setGuid(appUser.getName());
sysLog.setContent(methodDescp);
sysLog.setType(ELogType.Right);
}catch(Exception ex){
logger.error(ex.getMessage());
sysLog.setType(ELogType.Exception);
sysLog.setContent(ex.getMessage());
} finally{
sysLogBiz.saveSyslog(sysLog);
}
}
}
}
}
}
return point.proceed();
}
}
最后在你的配置文件中配置日志切面
<bean id="logAspect" class="advice.LogAspect"/>
<aop:config>
<aop:aspect ref="logAspect">
<aop:pointcut id="logPointCut" expression="execution(* web.action.*.*(..))"/>
<aop:around pointcut-ref="logPointCut" method="doSystemLog"/>
</aop:aspect>
</aop:config>
<aop:config proxy-target-class="true" />
</beans>
这是一个简单的系统日志功能,在你需要监控的方法上面如图所示,就可以完成记录的功能了