Spring自定义注解

Spring自定义注解

1.前置工作:

搭建一个springboot项目:https://blog.csdn.net/u013071014/article/details/110197639
运行项目,访问http://localhost:8080/user/3可正常获取到数据。

2.自定义注解

假设我们有如下需求,想要将调用的方法的详细信息打印在控制台,我们可以使用自定义注解实现。

1.创建自定义注解

新建一个annotation包,创建自定义注解PrintInfo

package com.example.demo.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PrintInfo {
	String value();
}
  • @Target 表示该注解用于什么地方,可能的 ElemenetType 参数包括:
    ElemenetType.CONSTRUCTOR 构造器声明
    ElemenetType.FIELD 域声明(包括 enum 实例)
    ElemenetType.LOCAL_VARIABLE 局部变量声明
    ElemenetType.METHOD 方法声明
    ElemenetType.PACKAGE 包声明
    ElemenetType.PARAMETER 参数声明
    ElemenetType.TYPE 类,接口(包括注解类型)或enum声明

  • @Retention 表示在什么级别保存该注解信息。可选的 RetentionPolicy 参数包括:
    RetentionPolicy.SOURCE 注解将被编译器丢弃
    RetentionPolicy.CLASS 注解在class文件中可用,但会被JVM丢弃
    RetentionPolicy.RUNTIME JVM将在运行期也保留注释,因此可以通过反射机制读取注解的信息。

  • @Documented:注解信息会被添加到Java文档中

2.将注解添加到方法上

@PrintInfo("这是一个function")
@RequestMapping("/{id}")
public UserMailVo getUserById(@PathVariable int id) {
    return userMailService.getUserById(id);
}

3.创建切面类

先在pom文件中添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

新建一个aop包,创建切面类PrintInfoAspect

package com.example.demo.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.example.demo.annotation.PrintInfo;

@Component
@Aspect
public class PrintInfoAspect {

	@Pointcut("@annotation(com.example.demo.annotation.PrintInfo)")
	private void pointcut() {}
	
	@Before("pointcut() && @annotation(info)")
	public void advice(JoinPoint joinPoint, PrintInfo info) {
		System.out.println("[" + joinPoint.getSignature().getDeclaringType() 
				+ "][" + joinPoint.getSignature().getName() + "]--->" 
				+ info.value());
	}
}

4.测试

重启项目后再次访问http://localhost:8080/user/3查看控制台的输出
在这里插入图片描述

5.最终代码结构

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值