在这这篇文章里面会降到两个知识点,一个是annotation 另一个就是Aop。我们先来实现一个记录日志的方法。
1 首先创建一个annotation接口:
@Target(ElementType.METHOD)//定义该注释标签作用对象为方法。
@Retention(RetentionPolicy.RUNTIME)//定义该注释标签保存范围为 JVM ,(保存范围还有 source(.java) 、class(.class))
@Documented //定义该注释标签后,此文件能够通过命令生成API文档
public @interface IUserLog {
/**
* 日志所属模块
*/
enum Module{
LOGIN("登录模块"),MANAGER("后台管理模块"),COMMAN("公共模块"),LOG("日志模块"),OTHER("其他模块");
Module(String title){
this.title = title;
}
/**
* 模块标题
*/
private String title;
public String getTitle() {
return title;
}
}
/**
* 当前要记录的日志属于什么模块
*/
Module model();
/**
* 操作名称
*/
String operation();
}
2 新建一个日志操作切面类
@Aspect //用这个标签标注切面类
@Component //把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>
public class UserLogAspect {
/**
* 注册切点
*/
@Pointcut("@annotation(com.zsq.cn.log.annotation.IUserLog)")
public void controllerLogAspect(){
}
@Before("controllerLogAspect()")
public void before(){
System.out.println("before IUserLog");
}
/**加入切点
* @param joinPoint
*/
@AfterReturning("controllerLogAspect()")
public void afterReturning(JoinPoint joinPoint){
IUserLog userLog = getUserLog(joinPoint);
System.out.println(userLog.model().getTitle());
System.out.println(userLog.operation());
}
@AfterThrowing(pointcut = "controllerLogAspect()",throwing = "e")
public void afterThrowing(JoinPoint joinPoint ,Exception e){
IUserLog userLog = getUserLog(joinPoint);
System.out.println(userLog.model().getTitle());
System.out.println(userLog.operation());
}
private IUserLog getUserLog(JoinPoint joinPoint) {
MethodSignature ms = (MethodSignature) joinPoint.getSignature();
Method method = ms.getMethod();
return method.getAnnotation(IUserLog.class);
}
}
3 在需要调用日志的方法上通过 “”@IUserLog(model = Module.LOG,operation = "测试日志")“” 标注即可
@IUserLog(model = Module.LOG,operation = "测试日志")
@RequestMapping("loginIn")
public String loginIn(HttpServletRequest requet,User user){
User user2 = loginService.loginIn(user);
requet.getSession().setAttribute(SessionNames.SESSION_USER, user2);
DataSourceUtils ds = (DataSourceUtils)ApplicationContextUtils.getBean("DataSourceUtilsBean");
System.out.println(ds.getDataSource().getActiveCount());
return "index/index";
}
4 在spring-mvc.xml文件中配置@Aspect切面的扫描
<!-- 有了这个Spring就能够自动扫描被@Aspect标注的切面了 -->
<aop:aspectj-autoproxy proxy-target-class="true" />
需要注意的是需要将 下面三句代码 粘贴到 <beans > 标签中
xmlns:aop="http://www.springframework.org/schema/aop"
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
这样 使用annotation和aop实现日志就完成了。要实现日志的持久化可以使用线程池(异步)去做