spring:注解配置AOP
注解配置AOP(使用 AspectJ 类库实现的),大致分为三步:
1. 使用注解@Aspect来定义一个切面,在切面中定义切入点(@Pointcut),通知类型(@Before, @AfterReturning,@After,@AfterThrowing,@Around).
2. 开发需要被拦截的类。
3. 将切面配置到xml中,当然,我们也可以使用自动扫描Bean的方式。这样的话,那就交由Spring AoP容器管理。
另外需要引用 aspectJ 的 jar 包: aspectjweaver.jar aspectjrt.jar
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
pom中的jar包支持
<!--spring-aop依赖 --><dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.4</version></dependency><dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.7.4</version></dependency><dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjtools</artifactId> <version>1.7.4</version></dependency><dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2</version></dependency>-----------------------------------------------------------------------------------------------------------------自定义注解Controller部分
package cn.cjq.util.aop; import java.lang.annotation.*; /** *自定义注解 拦截Controller */ @Target({ElementType.PARAMETER, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface SystemControllerLog { String description() default "";}---------------------------------------------------------------------------------------------------------------
自定义注解Service业务部分
package cn.cjq.util.aop;import java.lang.annotation.*;/** *自定义注解 拦截service */@Target({ElementType.PARAMETER, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface SystemServiceLog { String description() default "";}--------------------------------------------------------------------------------------------------------------------------------切面类
package cn.cjq.util.aop; import cn.cjq.entity.User;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.annotation.*;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;import java.lang.reflect.Method; /** * 切点类 * @author cjq * @since 2017-11-28 * @version 1.0 */@Aspect@Componentpublic class SystemLogAspect { //本地异常日志记录对象 private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect. class); //Service层切点 @Pointcut("@annotation(cn.cjq.util.aop.SystemServiceLog)") public void serviceAspect() { } //Controller层切点 @Pointcut("@annotation(cn.cjq.util.aop.SystemControllerLog)") public void controllerAspect() { } /** * 前置通知 用于拦截Controller层记录用户的操作 * * @param joinPoint 切点 */ @Before("controllerAspect()") public void doBefore(JoinPoint joinPoint) { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); HttpSession session = request.getSession(); //读取session中的用户 User user = (User) session.getAttribute("user"); //请求的IP String ip = request.getRemoteAddr(); try { //*========控制台输出=========*// System.out.println("=====前置通知开始====="); System.out.println("请求方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()")); System.out.println("方法描述:" + getControllerMethodDescription(joinPoint)); //System.out.println("请求人:" + user.getUsername()); System.out.println("请求IP:" + ip); //*========数据库日志=========*// /*Log log = SpringContextHolder.getBean("logxx"); log.setDescription(getControllerMethodDescription(joinPoint)); log.setMethod((joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()")); log.setType("0"); log.setRequestIp(ip); log.setExceptionCode( null); log.setExceptionDetail( null); log.setParams( null); log.setCreateBy(user); log.setCreateDate(DateUtil.getCurrentDate()); //保存数据库 logService.add(log);*/ System.out.println("=====前置通知结束====="); } catch (Exception e) { System.out.println("=====Controller通知结束====="); //记录本地异常日志 logger.error("==前置通知异常=="); logger.error("异常信息:{}", e.getMessage()); } } /** * 异常通知 用于拦截service层记录异常日志 * * @param joinPoint * @param e */ @AfterThrowing(pointcut = "serviceAspect()", throwing = "e") public void doAfterThrowing(JoinPoint joinPoint, Throwable e) { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); HttpSession session = request.getSession(); //读取session中的用户 User user = (User) session.getAttribute("user"); //获取请求ip String ip = request.getRemoteAddr(); //获取用户请求方法的参数并序列化为JSON格式字符串 String params = ""; if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) { for ( int i = 0; i < joinPoint.getArgs().length; i++) { params += joinPoint.getArgs()[i] + ";"; } } try { /*========控制台输出=========*/ System.out.println("=====异常通知开始====="); System.out.println("异常代码:" + e.getClass().getName()); System.out.println("异常信息:" + e.getMessage()); System.out.println("异常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()")); System.out.println("方法描述:" + getServiceMthodDescription(joinPoint)); //System.out.println("请求人:" + user.getUsername()); System.out.println("请求IP:" + ip); System.out.println("请求参数:" + params); /*==========数据库日志=========*/ /*Log log = SpringContextHolder.getBean("logxx"); log.setDescription(getServiceMthodDescription(joinPoint)); log.setExceptionCode(e.getClass().getName()); log.setType("1"); log.setExceptionDetail(e.getMessage()); log.setMethod((joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()")); log.setParams(params); log.setCreateBy(user); log.setCreateDate(DateUtil.getCurrentDate()); log.setRequestIp(ip); //保存数据库 logService.add(log);*/ System.out.println("=====异常通知结束====="); } catch (Exception ex) { System.out.println("=====Service通知结束====="); //记录本地异常日志 logger.error("==异常通知异常=="); logger.error("异常信息:{}", ex.getMessage()); } /*==========记录本地异常日志==========*/ logger.error("异常方法:{}异常代码:{}异常信息:{}参数:{}", joinPoint.getTarget().getClass().getName() + joinPoint.getSignature().getName(), e.getClass().getName(), e.getMessage(), params); } /** * 获取注解中对方法的描述信息 用于service层注解 * * @param joinPoint 切点 * @return 方法描述 * @throws Exception */ public static String getServiceMthodDescription(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 description = ""; for (Method method : methods) { if (method.getName().equals(methodName)) { Class[] clazzs = method.getParameterTypes(); if (clazzs.length == arguments.length) { description = method.getAnnotation(SystemServiceLog. class).description(); break; } } } return description; } /** * 获取注解中对方法的描述信息 用于Controller层注解 *@SystemControllerLog(description = "用户登录") 该方法获取描述部分
* @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 description = ""; for (Method method : methods) { if (method.getName().equals(methodName)) { Class[] clazzs = method.getParameterTypes(); if (clazzs.length == arguments.length) { description = method.getAnnotation(SystemControllerLog. class).description(); break; } } } return description; }}----------------------------------------------------------------------------------------------------------------------------------------xml配置支持
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" 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-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!--划红线的为配置aop必须的xml文件头 --> <aop:aspectj-autoproxy/> <!--这行对aop配置至关重要,且必须放在spring-mvc配置文件中方可生效 --> <!-- 自动扫描(自动注入) --> <context:component-scan base-package="cn.cjq.controller;cn.cjq.api;"/>
<mvc:annotation-driven /><!-- cache-period="315360000" -->--------------------------------------------------------------------------------------------------------
实例:Controller前置拦截
/** * 用户登录 */@ResponseBody()@RequestMapping(value = "userLogin")@SystemControllerLog(description = "用户登录")public Object userLogin( @RequestParam(value="userName",required=false,defaultValue="") String userName, @RequestParam(value="passWord",required=false,defaultValue="") String passWord, @RequestParam(value="rememberMe",required=false,defaultValue="0") boolean rememberMe, @RequestParam(value="validateCode",required=false,defaultValue="") String validateCode, @RequestParam(value="userType",required=false,defaultValue="") String userType ) throws Exception{ String error=null; Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(userName, passWord,rememberMe); try { subject.login(token); //如何能够访问到已经在 Realm 中获取到的 User 的实例. //Object principal = SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal(); } catch (UnknownAccountException e) { error = "用户名/密码错误"; } catch (IncorrectCredentialsException e) { error = "用户名/密码错误"; } catch (AuthenticationException e) { //其他错误,比如锁定,如果想单独处理请单独catch处理 error = "其他错误:" + e.getMessage(); } Map<Object, Object> result = new HashMap<Object, Object>(); if(error != null ){ result.put("success", false); result.put("message", error); }else{ User user = userServiceImpl.findByUserName(userName); Session sessions = subject.getSession(); sessions.setAttribute("user",user ); result.put("success", true); } return result;}
实例2:service异常拦截
/** * 根据用户名查询账号信息 */@SystemServiceLog(description = "查询账号信息异常")public User findByUserName (String username)throws Exception{ User user = new User(); List<User> accList = userMapper.findByUserName(username); if(accList.size()>0){ user = accList.get(0); }else{ user = null; } return user;}
转载于:https://www.cnblogs.com/1234cjq/p/7908764.html
spring:注解配置AOP相关推荐
- spring事务管理-注解配置aop事务(重点)
导包,导入新的约束,通知都不用配了,这两个是一样的,导包这一步,新的约束,tx这些都是一样的,第三步开始不同,这个注解配置大概一分钟就讲完了,第三步咱们可以开启注解,管理事务,那这块的话,咱们的配置文 ...
- Spring注解配置工作原理源码解析
一.背景知识 在[Spring实战]Spring容器初始化完成后执行初始化数据方法一文中说要分析其实现原理,于是就从源码中寻找答案,看源码容易跑偏,因此应当有个主线,或者带着问题.目标去看,这样才能最 ...
- Spring注解实现aop
需要aop的依赖 配置文件中需要激活: execution(* com.igeekhome.c30.aop.*.*(..)) 第一个*表示任意返回值 ,第二个*表示任意类, 第三个*表示任意方法,(. ...
- Spring 注解配置
2019独角兽企业重金招聘Python工程师标准>>> http://my.oschina.net/u/1157906/blog/178204 Spring的注解配置 转载于:ht ...
- 注解配置 AOP 详解
注解通知的类型 通知的配置语法:@通知注解("切点表达式") 2) 切点表达式的抽取 同 xml配置aop 一样,我们可以将切点表达式抽取.抽取方式是在切面内定义方法,在该方法上使 ...
- spring注解配置
使用注解配置需要引入xml文件约束条件 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns ...
- spring注解配置quartz
常规配置quartz可以参考我的另外一篇博文:http://www.cnblogs.com/yangzhilong/p/3349116.html spring配置文件里增加: 命令空间: http:/ ...
- [内容有误,请看参考和评论区]Spring 注解配置(annotation-config 和 component-scan的不同)
[内容有误,请看参考和评论区]Spring 的xml配置里如何仅通过注解使用(annotation-config 和 component-scan的不同) 这个问题也算看了好几遍还没记住的问题,先抛结 ...
- CXF的Spring注解配置及使用
使用的cxf包版本为 cxf-2.6.1.jar 官方下载地址:CXF下载地址 web.xml配置 <servlet><servlet-name>CXFServ ...
- 【Spring】Spring注解配置okhttp3
1.概述 maven引入如下 <dependency><groupId>com.squareup.okhttp3</groupId><artifactId&g ...
最新文章
- 排序算法——冒泡排序、选择排序、直接插入排序
- Mysql5.7 ZIP 压缩包非安装版的安装方式
- 互联网晚报 | 9月16日 星期四 | 网易云音乐发布“村民证”;阿里社区电商品牌升级为“淘菜菜”;高德打车上线“实景上车点”...
- 116_Power Pivot 先进先出原则库龄库存计算相关
- 《敏捷可执行需求说明 Scrum提炼及实现技术》—— 3.4 关注干系人的“愿求”...
- ViewHolder模式超简洁写法
- mybatis学习(二)
- 136、易燃固体的概念
- 调用百度API实现人脸识别
- 毕业步入职场,我是怎么用python自动化做到准时下班,薪资还高的
- 逢七过,逢七坐,逢七出列。。。 。。。各种叫法都有
- 用bat执行ps1脚本
- c语言strrchr函数,strrchr_字符串 | Strings_C_参考手册_非常教程
- 计算机操作系统复习资料
- js 进一法取正、四舍五入法取正、舍去法取正
- 《Deep Learning》中文翻译总结
- 微信短信验证码登录教程
- webmatrix mysql_WebMatrix PHP MySQL
- 爱普生Epson LX-310 打印机驱动
- 每日刷题:第四天 快乐数
热门文章
- Atiitt 兼容性提升的艺术 attilax总结 目录 1. 兼容性产生的原因	2 1.1. Api变化	2 1.2. 需求的资源不满足	2 2. 兼容性的分类	2 2.1. Web方面的兼容性
- Atitit 个人 企业 政府 等组织 财政收入分类与提升途径attilax总结 1.1. 国家财政收入分类	1 1.2. 企业收入分类	1 1.3. 个人收入分类	1 1.1.国家财政收入分类
- paip.python错误解决23
- paip.提升用户体验-----c++ 实现360浏览器收藏动作星星动画效果
- 《证券基金经营机构信息技术管理办法》要点简读
- 我们眼中的资管管理行业三要素
- Jibun 银行:一家纯网络银行,利用智能手机打开金融服务领域的新天地
- (转)谁是全球资管规模之冠?
- Julia :PyPlot库安装中需注意的问题
- 谁与争锋|神龙三代,集大成而来!