aop自定义切面
2016-03-30 15:15
411 查看
先定义注解
import java.lang.annotation.*; /** * Created by dubby on 16/3/23. */ @Target({ElementType.PARAMETER, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface SystemLog { String description() default ""; }
在实现切片
import com.ndkey.web.ResponseData; import com.nington.armstrong.aspect.annotation.SystemLog; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import javax.servlet.http.HttpSession; import java.lang.reflect.Method; import java.util.Objects; /** * Created by dubby on 16/3/23. */ @Aspect @Order(0) @Component public class SystemLogAspect { private static final Logger logger = LogManager.getLogger(); //切点 @Pointcut("@annotation(***.aspect.annotation.SystemLog)") public void aspect() { } @Around("aspect()") public Object around(JoinPoint joinPoint){ Object object = null; try{ object = ((ProceedingJoinPoint)joinPoint).proceed(); } catch (Throwable t){ logger.error(getMethodDescription(joinPoint) + " "+t.getMessage()); return ResponseData.errorData("server error"); } return object; } /** * 获取注解中对方法的描述信息 * * @param joinPoint 切点 * @return 方法描述 * @throws Exception */ public static String getMethodDescription(JoinPoint joinPoint) { String description = ""; try { String targetName = joinPoint.getTarget().getClass().getName(); String methodName = joinPoint.getSignature().getName(); Object[] arguments = joinPoint.getArgs(); Class targetClass = Class.forName(targetName); Method[] methods = targetClass.getMethods(); description = ""; for (Method method : methods) { if (method.getName().equals(methodName)) { Class[] clazzs = method.getParameterTypes(); if (clazzs.length == arguments.length) { description = method.getAnnotation(SystemLog. class).description(); break; } } } } catch (ClassNotFoundException e) { e.printStackTrace(); } return description; } }
使用切面
@RequestMapping("/hello") @SystemLog(description = "hello") @Transactional public ResponseData hello() { Role role = new Role(); role.setId(UUID.randomUUID().toString()); role.setName("测试"); roleMapper.insertSelective(role); role = new Role(); roleMapper.insert(role); return ResponseData.successData(role.getName()); }
相关文章推荐
- Linux(2):Linux系统关闭与重启
- Linux目录结构剖析说明
- 每天一个linux命令(5):xargs命令
- linux常用命令总结
- Rabbitmq的使用及Web监控工具使用
- log4j在tomcat项目与jboss项目中分类输出文件的总结
- linux动态库编译和使用详细剖析
- 关于vim/vi简单介绍
- 我的NopCommerce之旅(4): 定时任务之邮件
- 架构演化中的软件设计原则
- shell数组 只保留2个元素
- Nginx-启动脚本
- 几个linux命令记录
- NUMA架构的CPU -- 你真的用好了么?
- 大话Linux操作系统
- ECLIPSE JSP TOMCAT 环境搭建
- docker graphdriver之aufs
- tomcat部署时war和war exploded区别
- 【OpenCV】opencv 检测直线、圆、矩形
- 在linux中添加字体