您的位置:首页 > 编程语言 > Java开发

简单使用Spring的aop原理--案例

2018-07-24 17:15 459 查看

   首先,我们需要一个SSM的项目,这个我之前已经搭建好了。项目包路径如下:

今天这个案例是简单使用Spring的aop原理,假如项目现在所有Controller接收的参数都是加密后的,在使用前必须进行解密,如果在每个Controller中解密,就会有很多重复的代码。所以在这里使用aop的思想,在进入方法前进行对加密参数体解密,减少重复代码!(当然也可以对参数进行别的操作,这里只是以这个项目为例子 ...)

现在包路径下创建interceptor包,在包下创建我们的拦截器类DecodeAspect.java,如下:

package com.springmvc.interceptor;

import com.springmvc.util.DES3;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Arrays;

/**
* 用aop的思想,在进入方法前进行对加密参数体解密,减少重复代码
*/
@Aspect
@Order(100)
@Component("decodeAspect")
public class DecodeAspect {
private static final Logger logger = Logger.getLogger(DecodeAspect.class);

/**
* 环绕通知:目标方法执行前后分别执行一些代码,发生异常的时候执行另外一些代码
*
*/
@Around(value = "execution(* com.springmvc.controller.*.*(..))")
public Object aroundMethod(ProceedingJoinPoint jp) {

String methodName = jp.getSignature().getName();
Object result;
try {
logger.info("【Aspect前置通知】:the method 【" + methodName + "】 begins with " + Arrays.asList(jp.getArgs()));
Object[] obj = jp.getArgs();//获取接口所有参数
String param = (String) obj[0];
//此处可以对参数进行统一处理,解密字符串
String decodeStr = DES3.decode(param);
obj[0]=decodeStr;
//执行目标方法
result = jp.proceed(obj);
logger.info("【Aspect返回通知】:the method 【" + methodName + "】 ends with " + result);
} catch (Throwable e) {
logger.error("【Aspect异常通知】:the method 【" + methodName + "】 occurs exception " + e.getMessage());
result="出现异常:"+e.getMessage();
return result;
}
logger.info("【Aspect后置通知】:-----------------end.----------------------");
return result;
}
}

 在DecodeAspect中,我们获取接口的参数,然后对参数进行解密,接着在执行目标方法,这样就可以实现对所有Controller包下的接收的参数都是解密后的。

当然还少不了修改SpringMVC.xmld配置文件,如下:

 别忘了加上约束:

 下面我们在Controller中编写一个测试方法:

 最后,我们启动项目,用postman发送请求访问接口,传入DES3加密后的参数:

查看控制台结果:

 传入方法的参数已经解密,也不需要写多余的代码,是不是很神奇,哈哈哈!其实aop还有很多的用处的,这个小案例只是冰山一角。

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: