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

SpringBoot自定义注解,实现自定义方法

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

SpringBoot自定义注解,实现自定义方法

1.添加所需要的依赖

        
            org.springframework.boot
            spring-boot-starter-aop
        

2.包名目录如图所示

3.AddLog.java文件 (注解文件)

package com.aivoicetech.annotion;

import java.lang.annotation.*;


@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface AddLog {//Annotation 类型定义为@interface, 所有的Annotation 会自动继承java.lang.Annotation这一接口,并且不能再去继承别的类或是接口。  AddLog为注解名称

    
    String[] value() default {};

}

4.AddLogAop.java (自定义注解要实现的功能)

package com.aivoicetech.annotion;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
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.util.Arrays;


@Aspect
@Component
public class AddLogAop {

    private static final Log log = LogFactory.getLog(AddLogAop.class);

    
    @Pointcut("@annotation(com.aivoicetech.annotion.AddLog)")
    private void getAddLogPointCut() {
    }

    
    @Before("@annotation(addLog)")
    public void doAddLog(JoinPoint joinPoint,AddLog addLog) {
        String[] value = addLog.value();
        log.info("使用了注解,value值为:"+Arrays.toString(value));
    }

    
    @After("@annotation(addLog)")
    public void afterExecute(JoinPoint joinPoint,AddLog addLog) {
        log.info("方法执行完成...");
    }

}

5.TestController.java (测试注解)

package com.aivoicetech.controller;

import com.aivoicetech.annotion.AddLog;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class TestController {

    @GetMapping("/test")
    @AddLog(value = "123")
    public String test(){
        System.out.println("方法执行中。。。");
        return "test";
    }

}

访问该接口,控制台打印如下

由此可见,注解使用成功

通过本案例进行改造,可以完成注解的其它功能,例如:添加日志、参数校验等等

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

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

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