【SpringMVC】自定义注解(二)

简介: 【SpringMVC】自定义注解(二)

2.3.自定义注解

自定义注解类编写的一些规则:

  1.   Annotation 类型定义为@interface, 所有的Annotation 会自动继承java.lang.Annotation这一接口,并且不能再去继承别的类或是接口。
  2.  参数成员只能用public 或默认(default) 这两个访问权修饰。语法:类型  属性名()  [default 默认值];      default表示默认值 ,也可以不编写默认值的.
  3.  参数成员只能用基本类型byte、short、char、int、long、float、double、boolean八种基本数据类型和String、Enum、Class、annotations等数据类型,以及这一些类型的数组.
  4.  要获取类方法和字段的注解信息,必须通过Java的反射技术来获取 Annotation 对象,因为你除此之外没有别的获取注解对象的方法。
  5.  注解也可以没有定义成员,,不过这样注解就没啥用了。

注意: 自定义注解需要使用到元注解。

  • 注解方法不能有参数。
  • 注解方法的返回类型局限于原始类型,字符串,枚举,注解,或以上类型构成的数组。
  • 注解方法可以包含默认值。

 

2.3.1.自定义注解的分类

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

标记Annotation:

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

 

元数据Annotation:

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

三、注解取值的应用

3.1.前期准备工作

TranscationModel枚举类

1. public enum  TranscationModel {
2.     Read, Write, ReadWrite
3. }

小贴士什么是枚举类?枚举类的作用是什么?

枚举类是Java中一种特殊的数据类型,用于定义一组固定的命名常量。枚举类型提供了一种更强大、更安全和更易读的方式来表示一组相关的常量。在Java中,枚举类型是通过关键字`enum`来定义的。

枚举类的作用是提供一种类型安全的方式来表示一组固定的值,避免使用数字或字符串常量时可能出现的错误。通过使用枚举类型,可以限制变量只能取预定义的值,并且可以在代码中使用这些常量的名称来提高可读性和可维护性。

MyAnnotation1自定义注解类

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

MyAnnotation2自定义注解类

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

MyAnnotation3自定义注解类

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

TestAnnotation自定义注解类

//@Retention(RetentionPolicy.SOURCE)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface TestAnnotation {
    String value() default "默认value值";
    String what() default "这里是默认的what属性对应的值";
}

IsNotNull自定义注解类

/**
 非空注解:使用在方法的参数上,false表示此参数可以为空,true不能为空
 */
@Documented
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface IsNotNull {
    boolean value() default false;
}

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

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

运行list方法结果:

运行edit方法结果:


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

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(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方法结果:

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

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

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

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

运行hello1方法结果:

运行hello2方法结果:

运行hello3方法结果:

如果我们属性不为true,或者名字不为zs会怎样?

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

四、自定义注解案例

在写项目的过程中,肯定遇到过记录日志的功能要求,这时候我们就可以根据这个要求建立一个自定义注解类,只有被该注解修饰的方法就会走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);
    /**
     * 只要用到了com.javaxl.p2.annotation.springAop.MyLog这个注解的,就是目标类
     */
    @Pointcut("@annotation(com.csdn.xw.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层代码

@Component
public class LogController {
    @RequestMapping("/mylog")
    @MyLog(desc = "这是结合spring aop知识,讲解自定义注解应用的一个案例")
    public void testLogAspect(){
        System.out.println("这里随便来点啥");
    }
}

 

到这里我的分享就结束了,欢迎到评论区探讨交流!!

💖如果觉得有用的话还请点个赞吧 💖



相关实践学习
日志服务之使用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
|
5天前
|
前端开发 安全 Java
解锁高级技巧:玩转 Spring MVC 自定义拦截器的神奇世界
解锁高级技巧:玩转 Spring MVC 自定义拦截器的神奇世界
79 0
|
5天前
|
缓存 安全 Java
SpringMVC自定义注解和使用
SpringMVC自定义注解和使用
97 0
|
5月前
|
Java
springmvc之自定义注解-->自定义注解简介,基本案例和aop自定义注解
springmvc之自定义注解-->自定义注解简介,基本案例和aop自定义注解
34 0
|
5月前
|
Java 开发者
SpringMVC----自定义注解
SpringMVC----自定义注解
33 0
|
5月前
|
Java
【SpringMVC】之自定义注解
【SpringMVC】之自定义注解
36 0
|
6月前
|
JSON 安全 Java
SpringMVC之自定义注解(这期博客带你领略自定义注解的魅力)
SpringMVC之自定义注解(这期博客带你领略自定义注解的魅力)
47 0
SpringMVC之自定义注解(这期博客带你领略自定义注解的魅力)