1、开始 在Springboot框架中引入AOP
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2、创建注解 因需要在方法层面上进行控制 所以使用注解
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* 定义一个消息通知的注解类
* @version:
* @Description:
* @author: hyd
* @date: 2019年2月20日 下午12:00:54
*/
@Documented
@Retention(RUNTIME)
@Target(METHOD)
public @interface NotificationMessage {
}
注:在注解内部 可以添加自己需要的参数 ,具体怎么添加和设置默认值 请自行进行百度
3、创建切面类
/**
* 此类为一个切面类,主要作用就是对接口的请求进行拦截
* 拦截的方式,只需要在指定接口方法上面加上@NotificationMessage注解即可
*
*/
@Aspect
@Component
public class NotificationAop{
//使用org.slf4j.Logger,这是spring实现日志的方法
private final static Logger logger = LoggerFactory.getLogger(NotificationAop.class);
/**
* 表示在执行被@NotificationMessage注解修饰的方法之前 会执行doBefore()方法
*
* @param joinPoint 连接点,就是被拦截点
*/
@Before(value = "@annotation(com.example.demo.annotation.MonitorRequest)")
public void doBefore(JoinPoint joinPoint) {
//获取到请求的属性
ServletRequestAttributes attributes =
(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//获取到请求对象
HttpServletRequest request = attributes.getRequest();
//URL:根据请求对象拿到访问的地址
logger.info("url=" + request.getRequestURL());
//获取请求的方法,是Get还是Post请求
logger.info("method=" + request.getMethod());
//ip:获取到访问
logger.info("ip=" + request.getRemoteAddr());
//获取被拦截的类名和方法名
logger.info("class=" + joinPoint.getSignature().getDeclaringTypeName() +
"and method name=" + joinPoint.getSignature().getName());
//参数
logger.info("参数=" + joinPoint.getArgs().toString());
//获取切面方法的参数
joinPoint.getArgs();
//...添加自己的业务逻辑代码
}
/*
@After 等来控制 是在方法执行前执行还是在方法执行后执行
**/
}
4、如何使用
在对应的方法上加上这个注解即可
结束
5、创建枚举类记录
- 创建被final修饰的属性
- 提供全属性的构造方法
- 提供属性的get 方法
package com.zwxq.Enum;
/**
* 消息通知类型 枚举类
*
* @version:
* @Description:
* @author: hyd
* @date: 2019年2月20日 下午3:14:08
*/
public enum NotificationTypeEnum {
CONFESSIONTYPE("confession",1),
ROASTTYPE("roast",2);
private final String notificationName;
private final int type;
private NotificationTypeEnum(String notificationName, int type) {
this.notificationName = notificationName;
this.type = type;
}
public String getNotificationName() {
return notificationName;
}
public int getType() {
return type;
}
}