SpringMVC自定义注解

简介: SpringMVC自定义注解

一,Java注解简介

1.java注解的定义

Java注解是附加在代码中的一些元信息,用于一些工具在编译、

运行时进行解析和使用,起到说明、配置的功能。 注解相关类都

包含在java.lang.annotation包中。

2.Java注解分类

2.1JDK基本注解

@Override(重写)


@SuppressWarnings(value = "unchecked")  (压制编辑器警告)

2.2JDK元注解

@Retention:定义注解的保留策略
@Retention(RetentionPolicy.SOURCE)    //注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS)     //默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
@Retention(RetentionPolicy.RUNTIME)   //注解会在class字节码文件中存在,在运行时可以通过反射获取到

@Target:指定被修饰的Annotation可以放置的位置(被修饰的目标)
@Target(ElementType.TYPE)                      //接口、类
@Target(ElementType.FIELD)                     //属性
@Target(ElementType.METHOD)                    //方法
@Target(ElementType.PARAMETER)                 //方法参数
@Target(ElementType.CONSTRUCTOR)               //构造函数
@Target(ElementType.LOCAL_VARIABLE)            //局部变量
@Target(ElementType.ANNOTATION_TYPE)           //注解
@Target(ElementType.PACKAGE)                   //包
注:可以指定多个位置,例如:
@Target({ElementType.METHOD, ElementType.TYPE}),也就是此注解可以在方法和类上面使用

@Inherited:指定被修饰的Annotation将具有继承性

@Documented:指定被修饰的该Annotation可以被javadoc工具提取成文档.

2.3自定义注解

注解分类(根据Annotation是否包含成员变量,可以把Annotation分为两类):


标记Annotation:

没有成员变量的Annotation; 这种Annotation仅利用自身的存在与否来提供信息

理解:就是没有


元数据Annotation:

包含成员变量的Annotation; 它们可以接受(和提供)更多的元数据;

二,自定义注解

如何自定义注解?

使用@interface关键字, 其定义过程与定义接口非常类似, 需要注意的是:Annotation的成员变量在Annotation定义中是以无参的方法形式来声明的, 其方法名和返回值类型定义了该成员变量的名字和类型, 而且我们还可以使用default关键字为这个成员变量设定默认值

 

例如:SpringMVC已经定义好的:RequestMapping注解

@interface 是修饰注解类

@Target(决定自定义注解用在哪)

//ElementType.TYPE 指注解可以用在类上面

//ElementType.METHOD 指注解可以用在属性上面

//ElementType.FIELD 指用在方法上面

@Retention(定义注解的保留策略)

//RetentionPolicy.SOURCE注解仅存在于源码中,在class字节码文件中不包含

//RetentionPolicy.CLASS默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得

//RetentionPolicy.RUNTIME注解会在class字节码文件中存在,在运行时可以通过反射获取到

 

在注解类中定义的属性方法,都称为注解类的属性,我们接下来使用我们自定义的注解进行属性的使用,其中注解的属性为value时是可以省略的一般都会给一个default默认值

例如创建一个MyAnnotation1将其定义为可用在类、方法以及参数上:

package com.liyongan.annotation;
import java.lang.annotation.*;
/**
 * MyAnnotation1注解可以用在类、接口、属性、方法上
 * 注解运行期也保留
 * 不可继承
 */
@Target({ElementType.TYPE, ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation1 {
    String name();
}

MyAnnotation2:可用在方法上:

package com.liyongan.annotation;
import java.lang.annotation.*;
/**
 *  MyAnnotation2注解可以用在方法上
 *  注解运行期也保留
 *  不可继承
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation2 {
    TranscationModel model() default TranscationModel.ReadWrite;
}

MyAnnotation3:注解可以用在方法上,相比较MyAnnotation2多了一个注解@Inherited(可继承)

package com.liyongan.annotation;
import java.lang.annotation.*;
/**
 * MyAnnotation3注解可以用在方法上
 * 注解运行期也保留
 * 可继承
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyAnnotation3 {
    TranscationModel[] models() default TranscationModel.ReadWrite;
}

测试类:

Demo1测试类:

package com.liyongan.annotation.demo1;
import com.liyongan.annotation.MyAnnotation1;
import com.liyongan.annotation.MyAnnotation2;
import com.liyongan.annotation.MyAnnotation3;
import com.liyongan.annotation.TranscationModel;
/**
 * 获取类与方法上的注解值
 */
@MyAnnotation1(name = "abc")
public class Demo1 {
    @MyAnnotation1(name = "xyz")
    private Integer age;
    @MyAnnotation2(model = TranscationModel.Read)
    public void list() {
        System.out.println("list");
    }
    @MyAnnotation3(models = {TranscationModel.Read, TranscationModel.Write})
    public void edit() {
        System.out.println("edit");
    }
}

Demo1Test:

package com.liyongan.annotation.demo1;
import com.liyongan.annotation.MyAnnotation1;
import com.liyongan.annotation.MyAnnotation2;
import com.liyongan.annotation.MyAnnotation3;
import com.liyongan.annotation.TranscationModel;
import org.junit.jupiter.api.Test;
/**
 */
public class Demo1Test {
    @Test
    public void list() throws Exception {
//        获取类上的注解
        MyAnnotation1 annotation1 = Demo1.class.getAnnotation(MyAnnotation1.class);
        System.out.println(annotation1.name());//abc
//        获取方法上的注解
        MyAnnotation2 myAnnotation2 = Demo1.class.getMethod("list").getAnnotation(MyAnnotation2.class);
        System.out.println(myAnnotation2.model());//Read
//        获取属性上的注解
        MyAnnotation1 myAnnotation1 = Demo1.class.getDeclaredField("age").getAnnotation(MyAnnotation1.class);
        System.out.println(myAnnotation1.name());// xyz
    }
    @Test
    public void edit() throws Exception {
        MyAnnotation3 myAnnotation3 = Demo1.class.getMethod("edit").getAnnotation(MyAnnotation3.class);
        for (TranscationModel model : myAnnotation3.models()) {
            System.out.println(model);//Read,Write
        }
    }
}

Demo1目的:我们用来获取类注释上的类与方法上的注解值:

运行list方法结果:

运行edit方法结果:

Demo2目的:我们用来展示获取类属性上的注解属性值

Demo2测试类:

package com.liyongan.annotation.demo2;
import com.liyongan.annotation.demo1.TestAnnotation;
/**
 * 获取类属性上的注解属性值
 */
public class Demo2 {
    @TestAnnotation(value = "这就是value对应的值_msg1", what = "这就是what对应的值_msg1")
    private static String msg1;
    @TestAnnotation("这就是value对应的值1")
    private static String msg2;
    @TestAnnotation(value = "这就是value对应的值2")
    private static String msg3;
    @TestAnnotation(what = "这就是what对应的值")
    private static String msg4;
}

Demo2Test:

package com.liyongan.annotation.demo2;
import org.junit.jupiter.api.Test;
public class Demo2Test {
    @Test
    public void test1() throws Exception {
        TestAnnotation msg1 = Demo2.class.getDeclaredField("msg1").getAnnotation(TestAnnotation.class);
        System.out.println(msg1.value());
        System.out.println(msg1.what());
    }
    @Test
    public void test2() throws Exception{
        TestAnnotation msg2 = Demo2.class.getDeclaredField("msg2").getAnnotation(TestAnnotation.class);
        System.out.println(msg2.value());
        System.out.println(msg2.what());
    }
    @Test
    public void test3() throws Exception{
        TestAnnotation msg3 = Demo2.class.getDeclaredField("msg3").getAnnotation(TestAnnotation.class);
        System.out.println(msg3.value());
        System.out.println(msg3.what());
    }
    @Test
    public void test4() throws Exception{
        TestAnnotation msg4 = Demo2.class.getDeclaredField("msg4").getAnnotation(TestAnnotation.class);
        System.out.println(msg4.value());
        System.out.println(msg4.what());
    }
}

运行test1方法结果:

 

运行test2方法结果:

 

运行test3方法结果:

运行test4方法结果:

Demo3目的:我们用来展示获得获得属性上自定义注释中的内容:

Demo3测试类:

public class Demo3 {
    public void hello1(@IsNotNull(true) String name) {
        System.out.println("hello:" + name);
    }
    public void hello2(@IsNotNull String name) {
        System.out.println("hello:" + name);
    }
}

IsNotNull:

package com.liyongan.annotation.demo3;
import com.liyongan.annotation.demo3.Demo3;
import java.lang.annotation.*;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
/**
 * 非空注解:使用在方法的参数上,false表示此参数可以为空,true不能为空
 */
@Documented
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface IsNotNull {
    boolean value() default false;
}

Demo3Test:

public class Demo3Test {
    @Test
    public void hello1() throws Exception {
        Demo3 demo3 = new Demo3();
        for (Parameter parameter : demo3.getClass().getMethod("hello1", String.class).getParameters()) {
            IsNotNull annotation = parameter.getAnnotation(IsNotNull.class);
            if(annotation != null){
                System.out.println(annotation.value());//true
            }
        }
    }
    @Test
    public void hello2() throws Exception {
        Demo3 demo3 = new Demo3();
        for (Parameter parameter : demo3.getClass().getMethod("hello2", String.class).getParameters()) {
            IsNotNull annotation = parameter.getAnnotation(IsNotNull.class);
            if(annotation != null){
                System.out.println(annotation.value());//false
            }
        }
    }
    @Test
    public void hello3() throws Exception {
//        模拟浏览器传递到后台的参数 解读@requestParam
        String name = "zs";
        Demo3 demo3 = new Demo3();
        Method method = demo3.getClass().getMethod("hello1", String.class);
        for (Parameter parameter : method.getParameters()) {
            IsNotNull annotation = parameter.getAnnotation(IsNotNull.class);
            if(annotation != null){
                System.out.println(annotation.value());//true
                if (annotation.value() && !"".equals(name)){
                    method.invoke(demo3,name);
                }
            }
        }
    }
}

运行test1方法结果:

运行test2方法结果:

运行test3方法结果:

三,Aop自定义注解的应用

MyLog自定义注解类

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLog {
    String desc();
}

MyLogAspect切面类

@Component
@Aspect
public class MyLogAspect {
    private static final Logger logger = LoggerFactory.getLogger(MyLogAspect.class);
    @Pointcut("@annotation(com.liyongan.annotation.aop.MyLog)")
    private void MyValid() {
    }
    @Before("MyValid()")
    public void before(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        logger.debug("[" + signature.getName() + " : start.....]");
        System.out.println("[" + signature.getName() + " : start.....]");
        MyLog myLog = signature.getMethod().getAnnotation(MyLog.class);
        logger.debug("【目标对象方法被调用时候产生的日志,记录到日志表中】:"+myLog.desc());
        System.out.println("【目标对象方法被调用时候产生的日志,记录到日志表中】:" + myLog.desc());
    }
}

Controller层

@Controller
public class LogController {
    @RequestMapping("/mylog")
    @MyLog(desc = "这是结合spring aop知识,讲解自定义注解应用的一个案例")
    public void testLogAspect(){
        System.out.println("Tomcat运行乱码解决了!!!!");
    }
}

运行结果:

我们所编写的自定义注解类就可以走切面类。

四,总结

自定义注解可以用于多种场景。比如,我们可以创建一个自定义注解来限制请求的访问权限,或者用于数据验证、日志记录等。为了定义自定义注解,我们需要使用Java的@interface关键字,它表明我们正在定义一个注解。注解中可以定义属性,在使用注解时可以设置这些属性的值。

在Spring MVC中,我们可以自定义注解并将其应用到控制器的处理方法上,以实现某些特定的功能。比如,我们可以定义一个自定义的权限注解,来限制用户访问某个特定的处理方法。我们可以通过在注解中定义相关属性,如角色名称、权限级别等,然后在控制器方法上使用该注解。

相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
目录
相关文章
|
6月前
|
前端开发 Java 编译器
SpringMVC自定义注解---[详细介绍]
SpringMVC自定义注解---[详细介绍]
27 0
|
6月前
|
监控 Java 编译器
SpringMVC之自定义注解
SpringMVC之自定义注解
33 0
|
7月前
|
前端开发 Java
48SpringMVC - 参数绑定(自定义)
48SpringMVC - 参数绑定(自定义)
28 0
|
6月前
|
安全 Java 数据库连接
【springMvc】自定义注解的使用方式
【springMvc】自定义注解的使用方式
64 0
|
1天前
|
前端开发 安全 Java
解锁高级技巧:玩转 Spring MVC 自定义拦截器的神奇世界
解锁高级技巧:玩转 Spring MVC 自定义拦截器的神奇世界
79 0
|
1天前
|
缓存 安全 Java
SpringMVC自定义注解和使用
SpringMVC自定义注解和使用
95 0
|
5月前
|
Java
springmvc之自定义注解-->自定义注解简介,基本案例和aop自定义注解
springmvc之自定义注解-->自定义注解简介,基本案例和aop自定义注解
34 0
|
5月前
|
Java 开发者
SpringMVC----自定义注解
SpringMVC----自定义注解
29 0
|
5月前
|
Java
【SpringMVC】之自定义注解
【SpringMVC】之自定义注解
36 0
|
6月前
|
JSON 安全 Java
SpringMVC之自定义注解(这期博客带你领略自定义注解的魅力)
SpringMVC之自定义注解(这期博客带你领略自定义注解的魅力)
47 0
SpringMVC之自定义注解(这期博客带你领略自定义注解的魅力)