AOP记录系统日志log
AOP ,Aspect Oritentd Programing 面向切面编程
本质就是在不改变代码的基础上生成动态代理类(新类)
AOP记录日志实现步骤
- 编写测试类
- 编写业务层、dao层的增加日志的方法
- 在springmvc.xml中开启AOP自动代理
- 编写切面类记录日志
TestSyslogService
@Test
public void test02(){
Syslog syslog=new Syslog();
syslog.setUserName("tom");
syslog.setCompanyId("1");
syslog.setCompanyName("吉首大学");
syslog.setTime(new Date());
syslog.setIp("192.168.6.0");
syslog.setMethod("toList");
syslog.setAction("com.dsf.controller.system.syslog");
service.saveLog(syslog);
}
ISyslogService
void saveLog(Syslog syslog);
SyslogServiceImpl
@Override
public void saveLog(Syslog syslog) {
String id= UUID.randomUUID().toString();
syslog.setId(id);
dao.save(syslog);
}
ISyslogDao
void save(Syslog syslog);
ISyslogDao.xml
<insert id="save" parameterType="syslog">
insert into st_sys_log
(
id ,
user_name ,
ip ,
time ,
method ,
ACTION ,
company_id ,
company_name
)
values
(
#{id },
#{userName },
#{ip },
#{time },
#{method },
#{action },
#{companyId },
#{companyName }
)
</insert>
先测试保存方法
springmvc.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: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自动代理
<aop:aspectj-autoproxy/>
编写切面类LogAspect
@Aspect
@Component
public class LogAspect {
private Logger l= LoggerFactory.getLogger(LogAspect.class);
public LogAspect(){
l.info("LogAspect无参构造方法执行");
}
@Around(value = "execution(* com.dsf.web.controller..*.*Controller.*(..))")
public Object writeLog(ProceedingJoinPoint jp){
Object result=null;
try {
result = jp.proceed();
l.info("切面:writeLog");
saveSyslog(jp);
}catch (Throwable e){
}finally {
}
return result;
}
@Autowired
ISyslogService service;
@Autowired
HttpSession session;
@Autowired
HttpServletRequest request;
private void saveSyslog(ProceedingJoinPoint jp){
l.info("开始了");
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("sysLog=="+syslog);
service.saveLog(syslog);
}
}