前段时间根据业务需求要记录每次操作时的相关信息:本帖方式通过在SpringMVC中的Controller设置一个自定
义注解类来进行对数据的接收,通过 SpringAOP切面来对接收的数据进行逻辑处理.在事先根据业务需求创建的一个
实体类(如: UploadCount)的基础上:
1.首先springmvc.xml进行配置
<!-- 启动AOP AspectJ注解自动代理 -->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!-- 指定自定义注解类的路径 及 配置在Controller上添加自定义注解来接收数据 -->
<context:component-scan base-package="com.sl.api.common.util.aopUtils">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
2.根据业务需求创建自定义注解类
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface UploadCountLogs {
String moduleName() default ""; //自定义参数
}
3.创建一个对接收到的数据进行逻辑处理的切点类
/**
* 切点类
* @author shilei
* @version 1.0
*/
@Aspect
@Component
public class UploadCountLogsAspect{
//注入Service用于把上传记录的相关数据信息保存到数据库
@Autowired
private SchemeProposalsService schemeProposalsService;
@Autowired
private UserRedisUtils userRedisUtils;
//本地异常日志记录对象
//private static final Logger logger = LoggerFactory.getLogger(UploadCountLogsAspect. class);
//Controller层切点
@Pointcut("@annotation(com.sl.api.common.util.aopUtils.UploadCountLogs)")
public void controllerAspect() {
System.out.println("切入点...");
}
/**
* 前置通知 用于拦截Controller层 获取记录的操作信息
*
* @param joinPoint 切点
*/
@Before("controllerAspect()")
public void doBefore(JoinPoint joinPoint) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
User user = userRedisUtils.getUser(request);
try {
//具体业务逻辑 根据业务需求进行更改
UploadCount count = new UploadCount();
count.setTid(UUID.randomUUID().toString());
count.setModuleName(getControllerMethodDescription(joinPoint)[0]);
count.setCreateUid(user.getUserId().toString());
count.setDeptId(user.getDeptId());
count.setDeptName(user.getDept());
//保存数据库
schemeProposalsService.addRecord(count);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取注解中对方法的描述信息 用于Controller层注解
*
* @param joinPoint 切点
* @return 方法描述
* @throws Exception
*/
public static String[] getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
String[] annos = {""};
for (Method method : methods) {
if (method.getName().equals(methodName)) {
Class[] clazzs = method.getParameterTypes();
if (clazzs.length == arguments.length) {
annos[0] = method.getAnnotation(UploadCountLogs.class).moduleName();
//具体的业务逻辑 根据业务需求进行更改
if(annos[0].equals("新闻")){
Random random = new Random();
int ran = random.nextInt(30); //[0,30)
if (ran<10) {
annos[0]="政务公示";
}else if (ran>=10 && ran<20) {
annos[0]="政府舆情";
}else {
annos[0]="新闻数据";
}
}
break;
}
}
}
return annos;
}
}
4.最后在Controller加上自定义注解类,完成!!!
@UploadCountLogs(moduleName="新闻")