aop是什么
aop是面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。
为什么要用aop
利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
怎样使用aop到项目中
一、首先需要引入aop的pom依赖包
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.4</version>
</dependency>
<dependency><!--spring boot版-->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
二、日志实体类
public class Log {
//名字
private String name;
//时间
private String date;
//模块,功能
private String modular;
//行为
private String behavior;
//省略 get set...
}
三、使用自定义注解配置
/**
* 自定义注解
*/
//作用在方法上
@Target({ ElementType.METHOD})
//生命周期:编译后的class文件中存在,在jvm运行时保留,可以被反射调用
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAnnotation {
//模块的功能
Modular modular() ;
//人员的行为
Behavior behavior() ;
}
/**
* 功能类
*/
public enum Modular {
USER(1, "用户管理");
private int key;
private String value;
//构造
Modular (int key, String value) {
this.value = value;
this.key = key;
}
}
//省略 get set..
/**
* 行为类
*/
public enum Behavior {
SELECT(1, "查询"),
private int key;
private String value;
//构造
Behavior (int key, String value) {
this.value = value;
this.key = key;
}
}
//省略 get set..
四、定义切面
/**
* 日志AOP
*/
@Component
@Aspect
public class LogAspect {
@After(value = "@annotation(com.*.LogAnnotation)")//填写你的注解类地址
public void after(JoinPoint joinPoint) {
//获取抽象方法
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
//获取目标对象上的Method对象
Method method = methodSignature.getMethod();
//获取方法上的注解
LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
if (logAnnotation == null) {
logAnnotation = method.getDeclaringClass().getAnnotation(LogAnnotation.class);
}
if (logAnnotation != null) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
Object[] args = joinPoint.getArgs();//RequestBody参数 JSON.toJSONString(args)
// Enumeration<String> e = request.getParameterNames();
// StringBuilder req = new StringBuilder();
// while (e.hasMoreElements()) {
// String parameterName = e.nextElement();
// req.append(parameterName).append(": ").append(request.getParameter(parameterName));
// }
//模块
String modelName = logAnnotation.modelName().getValue();
//类型
String operType = logAnnotation.operType().getValue();
//获取用户
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
User user = (User) request.getSession().getAttribute("user");
//然后调用你的日志保存方法就ok了
//。。。
}
}
}
注意: @Component修饰的类必须要让xml文件的<context:component-scan>
扫描到,此类才会被注入生效
五、xml配置文件
springmvc配置文件需要加上下面的配置,才可以拦截到接口层的注解
<!--启动对@AspectJ注解的支持-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
注:要记得添加xml的头文件信息
六、接口层测试
在需要日志记录的方法上加上自定义的注解
@LogAnnotation(modular= Modular.USER, behavior= Behavior.SELECT)
public UserDto findUser() {
//接口逻辑·····
}
到此aop实现日志记录功能就全部写完了。
对不同的接口方法,只需要更改方法对应的枚举属性,日志就自动存入数据库了,非常方便。