Aop记录日志
- (1)什么是AOP
AOP ,Aspect Oritentd Programing 面向切面编程
本质就是在不改变代码的基础上生成动态代理类(新类)
- (2)应用场景
》日志记录
》事务管理
》权限管理
》性能数据记录
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ed826d0bac068711f032ffeb6e713db8.png#pic_center)
Aop记录日志实现
- (1)实现步骤
》编写日志切面类(@Aspect)
》编写springmvc.xml, 开启Aop自动代理
》测试Aop,自动记录日志 - (2)实现
LogAspect
编写日志切面类(@Aspect)
@Aspect
@Component
public class LogAspect {
private Logger l = LoggerFactory.getLogger(LogAspect.class);
public LogAspect() {
l.info("LogAspect 无参构造方法执行");
}
@Around(value = "execution(* com.lfy.web.controller..*.*Controller.*(..))")
public Object writeLog(ProceedingJoinPoint jp) {
Object result=null;
try{
result = jp.proceed();
l.info("切面:writeLog");
}catch (Throwable e){
}finally {
}
return result;
}
}
编写springmvc.xml, 开启Aop自动代理
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
...
...
<aop:aspectj-autoproxy/>
</beans>
在打印处调用保存
LogAspect
l.info("切面:writeLog");
saveSyslog(jp);
@Autowired
ISyslogService iSyslogService;
@Autowired
HttpSession session;
@Autowired
HttpServletRequest request;
private void saveSyslog(ProceedingJoinPoint jp) {
Syslog sysLog = new Syslog();
User user = (User) session.getAttribute("loginUser");
if(user != null){
sysLog.setUserName(user.getUserName());
sysLog.setCompanyId(user.getCompanyId());
sysLog.setCompanyName(user.getCompanyName());
}
sysLog.setIp(request.getRemoteAddr());
sysLog.setTime(new Date());
sysLog.setMethod(jp.getSignature().getName());
sysLog.setAction(jp.getTarget().getClass().getName());
l.info("saveSyslog sysLog="+sysLog);
iSyslogService.saveSyslog(sysLog);
}