1、依赖引入
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
2、新建自定义注解
package com.annotation.annotation; import com.annotation.constant.MessageType; import java.lang.annotation.*; /** * @author wuzhenyong * ClassName:Message.java * date:2022-05-23 14:06 * Description: */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Message { /** * 消息内容 */ public String content() default ""; /** * 发送人 */ public String sendUser() default "admin"; /** * 接收人 */ public String recvUser() default "admin"; /** * 自定义消息类型 */ public MessageType messageType() default MessageType.DEFAULT; }
3、新建消息类型枚举
package com.annotation.constant; /** * @author wuzhenyong * ClassName:MessageType.java * date:2022-05-23 14:09 * Description: */ public enum MessageType { /** * 消息类型 */ DEFAULT, ONE, TWO, THREE, }
4、新建aop切面类解析
package com.annotation.aop; import com.annotation.annotation.Message; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; import java.lang.reflect.Method; /** * @author wuzhenyong * ClassName:MessageAspect.java * date:2022-05-23 14:05 * Description: */ @Aspect @Component public class MessageAspect { /** * @annotation(注解类所在路径) */ @Pointcut("@annotation(com.annotation.annotation.Message)") public void sendMessagePointCut() { } /** * 获取方法上注解 */ @Before("sendMessagePointCut()") public void sendMessageBefor(JoinPoint joinPoint) { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); // 获取注解参数 Message annotation = method.getAnnotation(Message.class); System.out.println("before message :"); System.out.println(annotation); } @After("sendMessagePointCut()") public void sendMessageAfter(JoinPoint joinPoint) { } }
5、新建controller
package com.annotation.controller; import com.annotation.annotation.Message; import com.annotation.constant.MessageType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author wuzhenyong * ClassName:MessageController.java * date:2022-05-23 14:24 * Description: */ @RestController @RequestMapping("/message") public class MessageController { @GetMapping("/sendMessage") @Message(content = "发送信息", recvUser = "send1", messageType = MessageType.ONE) public String sendMessage() { return "发送成功"; } }
6、测试方法