自定义注解

目录

一、Java注解简介

1、Java注解分类

①、JDK基本注解

②、JDK元注解

③、自定义注解

2、如何自定义注解

二、自定义注解

1、注解类

①MyAnnotation1

②MyAnnotation2

2、StudentController

3、Demo1

 三、Aop自定义注解的应用

1、DemoController

2、MyLog

3、MyLogAspect

4、AnnotationTest


一、Java注解简介

1、Java注解分类

①、JDK基本注解

@Override
重写
@SuppressWarnings(value = “unchecked”)
压制编辑器警告

②、JDK元注解

@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工具提取成文档.

③、自定义注解

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

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

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

2、如何自定义注解

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

二、自定义注解

1、注解类

①MyAnnotation1

package com.zking.ssm.annotation;

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

/**
 * @author liaoxin
 * @create 2022-10-27 11:24
 */
@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation1 {
//    指的是注解的属性
    public String desc() default "desc可以修饰类、属性、方法";
    public String value() default "value可以修饰类、属性、方法";
}

②MyAnnotation2

package com.zking.ssm.annotation;

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

/**
 * @author liaoxin
 * @create 2022-10-27 11:24
 */
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation2 {
    //    指的是注解的属性
    public String desc() default "desc可以修饰类、属性、方法";
    public String value() default "value可以修饰类、属性、方法";
}

2、StudentController

package com.zking.ssm.annotation;

/**
 * @author liaoxin
 * @create 2022-10-27 11:29
 */
@MyAnnotation1(desc = "标记在类上面")
public class StudentController {

    @MyAnnotation1("标记在属性id上面")
    private String id;
    @MyAnnotation1("标记在属性name上面")
    private String name;

    @MyAnnotation1
    public void test1(@MyAnnotation2("标记在参数id中") String id,@MyAnnotation2("标记在参数name中") String name){
        System.out.println("测试");
    }
}

3、Demo1

package com.zking.ssm.annotation.demo;

import com.zking.ssm.annotation.MyAnnotation1;
import com.zking.ssm.annotation.MyAnnotation2;
import com.zking.ssm.annotation.StudentController;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * @author liaoxin
 * @create 2022-10-27 11:37
 *
 * 目标:
 * 1.获取StudentController 类上自定义注释中的内容
 * 2.获取StudentController 方法上自定义注释中的内容
 * 3.获取StudentController 属性上自定义注释中的内容
 * 4.获取StudentController 参数上自定义注释中的内容
 */
public class Demo1 {
    public static void main(String[] args) throws Exception {
//        获得类上自定义注释中的内容
        MyAnnotation1 annotation = StudentController.class.getAnnotation(MyAnnotation1.class);
        System.out.println(annotation.value());
        System.out.println(annotation.desc());

//        获得方法上自定义注释中的内容
        Method test1 = StudentController.class.getDeclaredMethod("test1", String.class, String.class);
        MyAnnotation1 m1 = test1.getAnnotation(MyAnnotation1.class);
        System.out.println(m1.value());

//        获得属性上自定义注释中的内容
        Field id = StudentController.class.getDeclaredField("id");
        Field name = StudentController.class.getDeclaredField("name");
        System.out.println(id.getAnnotation(MyAnnotation1.class).value());
        System.out.println(name.getAnnotation(MyAnnotation1.class).value());

//        获得参数上自定义注释中的内容
        for (Parameter p : test1.getParameters()) {
            System.out.println(p.getAnnotation(MyAnnotation2.class).value());
        }

//        Field[] declaredFields = StudentController.class.getDeclaredFields();
//        for (Field f : declaredFields) {
//            MyAnnotation1 annotation1 = f.getAnnotation(MyAnnotation1.class);
//            if(annotation1 != null){
//
//            }
//        }
    }
}

运行效果:
类:

 属性:

 方法:

参数:

 三、Aop自定义注解的应用

自定义注解的介入,可以在使用注解的地方,才触发aop切面
自定义注解日志的使用:

1、DemoController

package com.zking.ssm.annotation.aop;

import org.springframework.stereotype.Controller;

/**
 * @author liaoxin
 * @create 2022-10-27 14:41
 */
@Controller
public class DemoController {

    @MyLog(desc = "这是一个测试类的方法")
    public void test(){
        System.out.println("测试方法");
    }
}

2、MyLog

package com.zking.ssm.annotation.aop;

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

/**
 * @author liaoxin
 * @create 2022-10-27 14:40
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLog {
    String desc();
}

3、MyLogAspect

package com.zking.ssm.annotation.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.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author liaoxin
 * @create 2022-10-27 14:44
 */
@Component
@Aspect
public class MyLogAspect {
    private static final Logger logger = LoggerFactory.getLogger(MyLogAspect.class);

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

4、AnnotationTest

package com.zking.shiro;

import com.zking.ssm.annotation.aop.DemoController;
import com.zking.ssm.biz.ClazzBiz;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class AnnotationTest {
    @Autowired
    private DemoController demoController;

    @Test
    public void test1(){
        demoController.test();
    }

}

运行效果:

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值