AOP实战

最近要做一个历史记录的功能 让我一下子就想到了日志那一块 就用了下AOP  说实话 是真的好用 真的爽

springboot+jpa+spring 框架  话不多说 上代码

 

前提:pom文件里面加上aop的包

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>

package com.verify.demo.aop;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.verify.demo.annotations.HistoryAnnotation;
import com.verify.demo.entity.Admin;
import com.verify.demo.entity.SysHistory;
import com.verify.demo.repository.HistoryRepository;
import com.verify.demo.service.HistoryService;
import com.verify.demo.utils.httpclient.CommonUtils;
import com.verify.demo.utils.httpclient.DateUtils;

@Aspect
@Component
public class HistoryAopAction {
private final Logger logger = LoggerFactory.getLogger(HistoryAopAction.class);
@Autowired
private HistoryRepository historyRepository;
//自定义切点
//@Pointcut("execution(public * com.verify.demo.controller..*(..))")
//定义自定义 注解切点 这样的话 每个方法上只需要加上切点就可以使用aop了
@Pointcut("@annotation(com.verify.demo.annotations.HistoryAnnotation)")
private void pointCutMethod(){}

@After("pointCutMethod()") // 使用上面定义的切入点
public void recordLog(JoinPoint joinPoint) {
SysHistory sh=new SysHistory();
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
Admin user = (Admin) CommonUtils.getUser(request);
JSONObject jo=new JSONObject();
String s="";
//获取请求路径url
String requestURI = request.getRequestURI();

//获取页面传过来的参数k v
Map<String, String[]> parameterMap = request.getParameterMap();
Set<Entry<String,String[]>> entrySet = parameterMap.entrySet();
for (Entry<String, String[]> entry : entrySet) {
String key = entry.getKey();
String[] value = entry.getValue();
String value2=value[0];
jo.put(key, value2);

}
if(user == null){
logger.warn("user 信息为空");
}else{
sh.setUid(user.getAdminid());
sh.setCondtion(jo.toString());
sh.setModularurl(requestURI);
}

//记录历史记录
try {
Map<String,String> map = getHistoryMark(joinPoint);
sh.setIdentify(Integer.parseInt(map.get("identify")));
sh.setModularname(map.get("modularname"));
sh.setInserttime(DateUtils.getTimeStamp());
historyRepository.save(sh);
}catch (Exception e){
logger.error("插入日志异常",e.getMessage());
}
}

private Map<String,String> getHistoryMark(JoinPoint joinPoint) throws ClassNotFoundException {
Map<String,String> map = new HashMap<>();
String methodName = joinPoint.getSignature().getName();//获取切点的方法 two_element
String targetName = joinPoint.getTarget().getClass().getName();
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();//获取class中所有的方法
for (Method method : methods){
if(method.getName().equals(methodName)){

//标红的是自定义注解
HistoryAnnotation historyAnnotation = method.getAnnotation(HistoryAnnotation.class);
map.put("identify",historyAnnotation.identify());
map.put("modularname",historyAnnotation.modularname());
}
}
return map;
}
}

HistoryAnnotation 自定义注解

package com.verify.demo.annotations;

 

import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)//注解会在class中存在,运行时可通过反射获取
@Target(ElementType.METHOD)//目标是方法
public @interface HistoryAnnotation {
String url() default "";//url
String identify() default "";//模块标识
String modularname() default "";//模块名称

}

 

 

使用自定义注解

@HistoryAnnotation(identify="1",modularname="二要素验证")
@RequestMapping(value="/twoelement",produces="application/json;charset=UTF-8",method= RequestMethod.POST)
public Result two_element(@RequestParam("name") String name,@RequestParam("idcard") String idcard,HttpServletRequest request) {

............

}

 

这样的话 就实现了历史记录这个功能了   想要记录这个方法的历史记录 就只需要加下这个自定义注解就可以了

posted @ 2018-08-16 16:08  sysogg  阅读(166)  评论(0编辑  收藏  举报