SpringMVC自定义注解---[详细介绍]

一,对于SpringMVC自定义注解概念

       是一种特殊的 Java 注解,它允许开发者在代码中添加自定义的元数据,并且可以在运行时使用反射机制来获取和处理这些信息。在 Spring MVC 中,自定义注解通常用于定义控制器、请求处理方法、参数或者其他相关组件的行为

创建和使用由开发者自行编写,可以根据具体需求定义注解元素,并编写相应的注解处理器和逻辑来处理注解可用于标记特定的类、方法或参数

1.2 java注解的分类(主三种)

基本注解:

@Override:用于标记一个方法覆盖了父类或接口的方法。

@Deprecated用于标记一个类、方法或字段已经过时,不推荐使用。

@SuppressWarnings(value = "unchecked")用于抑制编译器产生的警告信息

元注解:

@Retention指定注解的生命周期,包括 RetentionPolicy.SOURCERetentionPolicy.CLASS 和 RetentionPolicy.RUNTIME

@Target指定注解的应用目标,包括 ElementType.TYPEElementType.FIELD

ElementType.METHOD 等。

@Documented指示注解是否包含在 Java 文档中。

@Inherited指示注解是否可以被继承。

@Repeatable指示注解可以多次应用于同一元素。

注:可以指定多个位置,例如:
@Target({ElementType.METHOD, ElementType.TYPE}),也就是此注解可以在方法和类上面使用

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

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

自定义注解:

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

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

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

注意:自定义注解只是一种提供元数据的机制,具体的处理逻辑需要通过注解处理器来实现。在使用自定义注解时,需要编写注解处理器来解析注解,并执行相应的行为。

1.3 如何使用自定义注解

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

二,使用自定义注解

案例一(获取类与方法上的注解值)

定义一个Package名为annotation包定义TranscationModel类

package com.Bingzy.annotation;

public enum  TranscationModel {
    Read, Write, ReadWrite;
    private Integer id;
    private String name;
    public void init1(){
        Read.id=1;
        Read.name="zs";
    }

    public void init2(){
        Write.id=2;
        Write.name="lisi";
    }

    public void init3(){
        ReadWrite.id=3;
        ReadWrite.name="wangwu";
    }
}

在annotation包下再创建测试类test01:

package com.Bingzy.annotation;

/**
 * @Name BingBing
 * @company zking cy
 * @create 2023-09-14-19:43
 */
public class Test01 {

    public static void main(String[] args) {
        System.out.println(TranscationModel.Read);
        System.out.println(TranscationModel.Write);
        System.out.println(TranscationModel.ReadWrite);
    }
}

在annotation包下再创建一个Package包Demo01 方便测试案例一:

创建三个注解类:

MyAnnotation1类:

@Target({ElementType.TYPE, ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation1 {
    String name();
}

MyAnnotation2类:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation2 {
    TranscationModel model() default TranscationModel.ReadWrite;
}

MyAnnotation3类:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyAnnotation3 {
    TranscationModel[] models() default TranscationModel.ReadWrite;
}

在Demo01包下创建测试类代码

Demo1:

@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:

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
        }
    }
}

测试结果:

案例二(获取类属性上的注解属性值)

注解类:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface TestAnnotation {
    String value() default "默认value值";

    String what() default "这里是默认的what属性对应的值";
}

测试类Demo2类

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:

public class Demo2Test {
    @Test
    public void test1() throws Exception {
        TestAnnotation msg1 = Demo2.class.getDeclaredField("msg1").getAnnotation(TestAnnotation.class);
        System.out.println("test1");
        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("test2");
        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("test3");
        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("test4");
        System.out.println(msg4.value());
        System.out.println(msg4.what());
    }
}

总结:如果我们注解上没有指定是value还是what默认就是value,如果只想转递一个参数又不想默认是value那就需要指定what=""即可。 

 案例三(获取参数修饰注解对应的属性值)

注解类:

@Documented
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface IsNotNull {
    boolean value() default false;
}

测试类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);
    }
}

测试类DemoTest3:

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);
                }
            }
        }
    }
}

运行结果: 

 

总结:这个案例像不像我们的注解@RequestParam必须传递参数,除非指定required为false就可与不传参数,我们这个案例也是如此。 

三,Aop自定义注解

定义一个注解类:

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

切面类:

@Component
@Aspect
public class MyLogAspect {
    private static final Logger logger = LoggerFactory.getLogger(MyLogAspect.class);

    /**
     * 只要用到了com.javaxl.p2.annotation.springAop.MyLog这个注解的,就是目标类
     */
    @Pointcut("@annotation(com.Bingzy.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("这里随便来点啥");
    }
}

运行结果:

猜你喜欢

转载自blog.csdn.net/m0_73192864/article/details/132888045