springboot自定义注解开发总结

学而时习之,不亦说乎,spring框架有两大特性IOC和AOP,对应着两大主要功能:对象管理和面向切面扩展功能,IOC通过反射机制和工厂模式实现,分析源码的帖子到处都是,没什么好说的。AOP是Spring框架面向切面的编程思想,AOP采用一种称为“横切”的技术,将涉及多业务流程的通用功能抽取并单独封装,形成独立的切面,在合适的时机将这些切面横向切入到业务流程指定的位置中。今天主要想说一下基于AOP的自定义注解的实现,作为平时工作总结,也分享给大家。

最常见的AOP应用场景是日志埋点,一般在业务完成之前,会记录一些操作内容,本次就以记录日志为例,实现自定义注解开发。

1.导入依赖包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
    <version>2.2.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
</dependency>

2.自定义注解接口

import java.lang.annotation.*;
//注解信息会被添加到Java文档中
@Documented 
//注解的生命周期,表示注解会被保留到什么阶段,可以选择编译阶段、类加载阶段,或运行阶段
@Retention(RetentionPolicy.RUNTIME) 
//注解作用的位置,ElementType.METHOD表示该注解仅能作用于方法上
@Target(ElementType.METHOD) 
public @interface WriteLog {
    String value() default "";
}

3.编写切面类

import java.util.Arrays;

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 com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Component
@Aspect
public class WriteLogAspect {
    

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    
  /**
   * 其中@Pointcut声明了切点(这里的切点是我们自定义的注解类),
   * @Before声明了通知内容,在具体的通知中,我们通过@annotation(logger)拿到了自定义的注解对象,
   * 所以就能够获取我们在使用注解时赋予的值了。
   */
	
    @Pointcut("@annotation(com.tzy.springboot.anno.WriteLog)")
    private void pointcut() {}
    
    @Before("pointcut() && @annotation(logger)")
    public void before(JoinPoint joinPoint,WriteLog logger) {
    	 //类名
    	 String clsName=joinPoint.getSignature().getDeclaringType().getSimpleName();
         //方法名
         String modName= joinPoint.getSignature().getName();
         //参数
         Object[] args = joinPoint.getArgs();
         StringBuffer result = new StringBuffer();
         result.append("["+clsName+"]");
         result.append("["+modName+"]");
         Arrays.stream(args).forEach(arg->{
             try {
             	result.append("["+OBJECT_MAPPER.writeValueAsString(arg)+"]");
             } catch (JsonProcessingException e) {
                 
             }
         });
         System.out.println(result.toString());
    }
    
}

4.使用自定义的注解

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.tzy.springboot.anno.WriteLog;
import com.tzy.springboot.common.ReturnItemUtils;
import com.tzy.springboot.common.pojo.ReturnItem;

/**
 * Created by tzy on 2019/10/16.
 * 
 */
@SuppressWarnings("rawtypes")
@RestController
@RequestMapping("/pernas/test")
public class TestController {
	 @SuppressWarnings("finally")
	 @WriteLog()
	 @GetMapping("/test")
	 public ReturnItem select(@RequestParam(name = "token") String token,
	     	 @RequestParam(name = "aaa",required = false) String aaa,
	     	 @RequestParam(name = "bbb",required = false) Integer bbb) {
		
		try {
			
			System.out.println("======ing.aaa:"+aaa);
		 }catch (Exception e) {
			 
		 }finally {
			 return ReturnItemUtils.newSuccessReturnItem();
		}
		
	 }
	
}

5.运行,输入参数,输出结果

[TestController][select]["68f033399105b740b3537bcdc8b87971"]["111"][222]
======ing.aaa:111

总结一下:引入的依赖是AOP的spring下的实现封装包,切面类中实现自定义注解接口的功能,然后就可以在你要使用注解功能的方法上使用了。使用自定义注解可以充分复用某些功能,减少代码量,降低耦合,丰富业务扩展,值得大量使用。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值