栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring项目中自定义注解的使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring项目中自定义注解的使用

Java在Jdk1.5中引入了注解,Spring框架也正好把Java注解发挥得淋漓尽致。
接下来简单介绍如何在Spring中自定义注解,其中会使用到Spring框架中的AOP(面向切面编程)。

一、创建自定义注解
package org.spring.springboot.config;

import java.lang.annotation.*;

@documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TestLog {
    
    String value() default "";
}
二、解析注解

接着完成注解的解析工作,这里使用了Spring的AOP(面向切面编程)特性
通过@Aspect注解使该类成为切面类。
通过@Pointcut 指定切入点 ,这里指定的切入点为TestLog注解类型,也就是被@TestLog注解修饰的方法,进入该切入点。

package org.spring.springboot.config;

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.springframework.stereotype.Component;
import java.lang.reflect.Modifier;

@Component
@Aspect
public class TestLogAspect {
    @Pointcut("@annotation(org.spring.springboot.config.TestLog)")
    private void pointcut() {}

    @Before("pointcut() && @annotation(logger)")
    public void advice(JoinPoint joinPoint, TestLog logger) {
        System.out.println("--- TestLog日志的内容为[" + logger.value() + "] ---");
        System.out.println("注解作用的方法名: " + joinPoint.getSignature().getName());
        System.out.println("所在类的简单类名: " + joinPoint.getSignature().getDeclaringType().getSimpleName());
        System.out.println("所在类的完整类名: " + joinPoint.getSignature().getDeclaringType());
        System.out.println("目标方法的声明类型: " + Modifier.toString(joinPoint.getSignature().getModifiers()));
    }
}
三、使用自定义注解
    @TestLog("自定义注解的输出日志内容8888888888888")
    @RequestMapping("/selectByPageTest")
    public IPage selectByPage(){
        return null;
    }
四、测试结果



参考文章
Spring项目中自定义注解的使用
Spring 自定义注解的实现

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/328956.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号