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

自定义注解实现

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

自定义注解实现

在Spring Boot项目中可以使用AOP实现自定义注解,从而实现统一、侵入性小的自定义功能。

比如我们实现一个统一打印日志的自定义注解

引入依赖

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



        
            com.google.guava
            guava
            18.0
        

        
            com.alibaba
            fastjson
            1.2.54
        
项目结构
D:JAVA-RES
├─.idea
│  └─libraries
├─.mvn
│  └─wrapper
├─src
│  ├─main
│  │  ├─java
│  │  │  └─yeye
│  │  │      └─devops
│  │  │          ├─annotation
│  │  │          ├─config
│  │  │          ├─control
│  │  │          ├─model
│  │  │          └─service
│  │  └─resources
│  │      ├─static
│  │      └─templates
│  └─test
│      └─java
│          └─yeye
│              └─devops
└─target
    ├─classes
    │  └─yeye
    │      └─devops
    │          ├─annotation
    │          ├─config
    │          ├─control
    │          ├─model
    │          └─service
    ├─generated-sources
    │  └─annotations
    ├─generated-test-sources
    │  └─test-annotations
    └─test-classes
        └─yeye
            └─devops
PS D:>

定义注解

定义注解的属性:

package yeye.devops.annotation;

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@documented
public @interface TraceLog {
    
    String business();

    
    String module();
}

定义切面
package yeye.devops.annotation;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableList;
import lombok.extern.slf4j.Slf4j;
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.util.List;

@Aspect
@Component
@Slf4j

public class TraceLogSupport {

    @Pointcut("@annotation(yeye.devops.annotation.TraceLog)")
    private void pointcut() {
    }

    @Before("pointcut()&&@annotation(traceLog)")
    public void before(JoinPoint joinPoint, TraceLog traceLog) {
        Object[] args = joinPoint.getArgs();
        log.error(generateLog(traceLog, JSON.toJSonString(args)));
    }

    private String generateLog(TraceLog traceLog, String args) {
        List elements = ImmutableList.of(
                traceLog.business(),
                traceLog.module(),
                args
        );
        return String.join(";", elements);
    }


}
入参实体
package yeye.devops.model;

import lombok.Data;

@Data
public class LoginParam {
    private String username;
    private String password;
}
验证
curl http://127.0.0.1:8080/login?username=knight&password=zlong

# 结果返回
LoginParam(username=knight, password=zlong)

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

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

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