天天看点

SpringBoot自定义注解AnnotationSpringBoot自定义注解Annotation

SpringBoot自定义注解Annotation

1. 编写一个自定义的注解类

在SpringBoot工程下新建一个annotation的package,在里面新建java class,kind中选择annotation,代码如下:

package com.example.demo.annotation;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Documented           //是否将注释信息添加在Java文档中
@Retention(RUNTIME)   //自定义的注释通常使用这种注释 RUNTIME
@Target(METHOD)       //将自定义注释放在什么地方,有一些枚举值
public @interface LoginAnno {     //该注解用来申明一个注解

}
           

2. 编写该注解的实现类

在同一个package下,编写LoginAnnoImpl类,目的是让该类成为切面类,具体可参考AOP

package com.example.demo.annotation;

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

/**
 * <h5>描述:通过@Aspect注解使该类成为切面类</h5>
 */
@Aspect
@Component
public class LoginAnnoImpl {

    @Pointcut("@annotation(com.example.demo.annotation.LoginAnno)")
    private void cut() {
    //@Pointcut定义的是切点
    }

    /**
     * <h5>功能:前置通知</h5>
     */
    @Before("cut()")       
    public void before() {
        System.out.println("自定义注解生效了");
    }
}

           

3. 可以编写一个控制器来检测该自定义注解是否生效

在控制层下面的文件里编写方法

@RequestMapping("login")
    @LoginAnno
    public String login(String userName) {
        return "欢迎您:" + userName;
    }
           

启动服务器,访问http://localhost:8080/login/niu

SpringBoot自定义注解AnnotationSpringBoot自定义注解Annotation

也可以加上参数

http://localhost:8080/login?userName=niu

SpringBoot自定义注解AnnotationSpringBoot自定义注解Annotation

至此,自定义注解完成