第一步:创建aop.xml的文件,启用aop
<?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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 启用 aop -->
<aop:aspectj-autoproxy proxy-target-class="true" />
</beans>
第二步:创建class 类上加上两个注解 @Component @Aspect
ppackage org.jeecgframework.core.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.jeecgframework.core.util.LogUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class LogMonitoring {
private static final Logger logger = LoggerFactory.getLogger(LogMonitoring.class);
@Autowired
private SystemService systemService;
@Pointcut("execution(* com.*.controller.*.*(..))")
public void recordLog() {
LogUtil.info("AOP切入成功 ");
}
@AfterReturning(pointcut = "recordLog()")
public void simpleAdvice() {
// LogUtil.info("AOP后处理成功 ");
}
@Around("recordLog()")
public Object aroundLogCalls(ProceedingJoinPoint jp) throws Throwable {
// LogUtil.info("正常运行");
return jp.proceed();
}
@Before("recordLog()")
public void before(JoinPoint jp) {
String className = jp.getThis().toString();
String methodName = jp.getSignature().getName(); // 获得方法名
LogUtil.info("位于:" + className + "调用" + methodName + "()方法-开始!");
Object[] args = jp.getArgs(); // 获得参数列表
if (args.length <= 0) {
LogUtil.info("====" + methodName + "方法没有参数");
} else {
for (int i = 0; i < args.length; i++) {
LogUtil.info("====参数 " + (i + 1) + ":" + args[i]);
}
}
LogUtil.info("=====================================");
// systemService.addLog();
// systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
}
@AfterThrowing("recordLog()")
public void catchInfo() {
// LogUtil.info("异常信息");
}
@After("recordLog()")
public void after(JoinPoint jp) {
// LogUtil.info("" + jp.getSignature().getName() + "()方法-结束!");
// LogUtil.info("=====================================");
}
}
execution()是最常用的切点函数,其语法如下所示:
整个表达式可以分为五个部分:
1、execution(): 表达式主体。
2、第一个*号:表示返回类型,*号表示所有的类型。
3、包名:表示需要拦截的包名,后面的两个句点表示当前包和当前包的所有子包,com包、子孙包下所有类的方法。
4、第二个*号:表示类名,*号表示所有的类。
5、*(…):最后这个星号表示方法名,*号表示所有的方法,后面括弧里面表示方法的参数,两个句点表示任何参数。
注意检查启动时是否加载了aop.xml 是否扫描了controller,注入bean