Spring AOP与自定义注解Annotation的使用

AOP,Spring框架的两大核心之一,又称面向切面编程,通过代理模式,对原有的类进行增强。在Spring框架中,AOP有两种动态代理方式,其一是基于JDK的动态代理,需要代理的类实现某一个接口;其二是基于CGLIB的方式,该方式不需要类实现接口就能进行代理。AOP的应用场景,常见的就是事务的处理和日志的记录,还有权限的认证。(笔者使用AOP的场景:保存所有用户对数据进行的增删改内容等,比如,张三修改了一个表格数据的值,就需要记录谁,什么时候,修改or添加or删除,哪项数据,数据的旧值和新值是什么。因为涉及到的接口很多,也很分散,所以笔者使用aop和自定义注解,让所有涉及到增删改的接口添加自定义注解,以达到在保存记录之后进行操作日志记录。)

Annotation,自定义注解,基于Java六大元注解的注解(target、document、retention、inherited、repeatable和类型注解)。一般创建自定义注解,至少会在该注解上添加@target(注解的位置,如添加到方法上或者是类上)和@retention(注解使用的时机,编译期间或者运行时等)俩个注解。

一、自定义注解

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

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface OperationLog {
    //表示操作是那个服务哪个模块下的操作
    String module() default "xxxx服务";

    //操作的类型,添加,更新,删除
    String type() default "add";

    //操作者
    String user() default "system";

    //操作描述
    String operation() default "";
}

二、Aspect类

import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;

@Aspect
@Component
public class OperationLogAspect {
    private ThreadLocal<SimpleDateFormat> format = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    
    //切点表达式,表示加了OperationLog注解的都是切点,路径是自定义注解的全路径
    @Pointcut("@annotation(com.alice.springboot.demo.OperationLog)")
    public void pointcut()
    {
        
    }
    
    @Around("@annotation(operationLog)")
    public Object operationLogRecord(ProceedingJoinPoint joinPoint, OperationLog operationLog)
    {
        //获取请求
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //响应
        ResponseResult<Object> responseResult = null;
        //判断原方法是否正常执行的标志
        boolean isNormalProcess = false;
        
        try 
        {
            //返回切点处继续执行原方法,并接收原方法的响应
            responseResult = (ResponseResult<Object>) joinPoint.proceed();    
            //如果顺利执行,那么说明原方法执行正常,就可以进行日志记录。因为,如果原方法的增删改出问题了,那么日志就不需要记录了,不用记录失败的操作。
            isNormalProcess = true;
        }
        catch (Throwable e)
        {
            System.out.println("原方法报错,不需要记录日志");
        }
        
        try 
        {
            if (isNormalProcess)
            {
                //如果原方法正常执行完毕,那么需要记录操作日志
                saveOperationLog(joinPoint, operationLog, request);
            }
        }
        catch (Exception e)
        {
            System.out.println("保存操作日志出错");
        }
        
        return  responseResult;
    }
    
    private void saveOperationLog(ProceedingJoinPoint joinPoint, OperationLog operationLog, HttpServletRequest request)
    {
        //用来记录参数的值
        StringBuilder contentBuilder = new StringBuilder();
        //从切点获取切点的所有参数
        Object[] allParams = joinPoint.getArgs();
        
        for (Object param: allParams)
        {
            contentBuilder.append(JSON.toJSONString(param) + ",");
        }
        //删除最后一个多余的逗号
        contentBuilder.delete(contentBuilder.length() - 1, contentBuilder.length());
        
        //执行数据库操作,将信息保存到数据库,笔者这里使用的是mongodb,仅供参考,主要看获取自定义注解里面的值
        Document document = new  Document();
        //获取自定义注解里面的值
        document.append("module", operationLog.module())
                .append("type", operationLog.type())
                .append("user", operationLog.user())
                .append("operation", operationLog.operation())
                .append("content", contentBuilder.toString());
        
        logDao.saveLogs("mongo collection name", document);
    }
    
}

三、如何使用——controller层使用

package com.alice.springboot.demo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/test")
public class OperationLogController {

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @OperationLog(module = "xxx服务", type = "add", operation = "添加xxx")
    //这里使用到了自定义注解,并且赋值了自定义注解里面的某些值,最后在aspect里面可以获取到这些值
    public ResponseResult<String> addOperation(String user, String content)
    {
        ResponseResult<String> result = new ResponseResult<>();

        try
        {
            //执行添加操作
            result.setStatus(ResponseStatusEnum.SUCCESS);
            result.setMessage("添加操作成功");
        }
        catch (Exception e)
        {
            result.setStatus(ResponseStatusEnum.FAIL);
            result.setMessage("添加操作失败" + e.toString());
        }

        return result;
    }
}

以上就是Spring APO结合自定义注解的使用。

  • 5
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用Spring AOP来通过自定义注解来实现切入点。首先,定义一个自定义注解,并在需要切入的方法上使用该注解,然后定义一个切面,并在切面中使用@Before 或 @Around 注解来拦截被标记的方法,最后,在Spring的配置文件中声明所需的切面,此时,所有被标记的方法都会被拦截。 ### 回答2: 使用Spring AOP切入自定义注解有以下几个步骤: 1. 在项目中引入Spring AOP的依赖,一般为spring-aopspring-aspects。 2. 在配置文件中开启Spring AOP的自动代理功能。可以通过在XML配置文件中添加<aop:aspectj-autoproxy />或在Java配置文件中添加@EnableAspectJAutoProxy注解实现。 3. 创建一个切面类,用于定义切入的逻辑。这个类需要使用@Component或者其他Spring注解进行标识,以便Spring能够扫描到。 4. 在切面类的方法中,使用@Before、@After等注解定义切入点和具体的切入操作。例如,使用@Before注解定义在某个注解标记的方法执行之前切入的逻辑。 5. 在注解中定义自定义的切点。可以使用@Retention和@Target等元注解来配置注解的生命周期和使用范围。 6. 在目标类或方法上添加自定义的注解。例如,在一个Service类的某个方法上添加自定义注解。 7. 运行项目,Spring会根据配置自动代理目标类,当目标类或方法被调用时,切面类中定义的切入逻辑就会自动被执行。 8. 可以通过配置切入的顺序、通知的类型等来进一步细化切入的逻辑。 通过以上步骤,我们可以使用Spring AOP方便地切入自定义注解,实现对目标类或方法的增强、日志记录、权限控制等功能。 ### 回答3: 使用Spring AOP切入自定义注解需要以下几个步骤: 1. 定义一个自定义的注解。可以使用Java提供的`@interface`关键字创建一个注解,例如: ```java @Target(ElementType.METHOD) // 定义注解的作用范围为方法 @Retention(RetentionPolicy.RUNTIME) // 注解在运行时可见 public @interface CustomAnnotation { // 自定义注解的属性 } ``` 2. 创建一个切面类来处理注解。可以使用Spring提供的`@Aspect`注解来标记切面类,并在方法上使用`@Before`、`@After`等注解来定义切入点和增强逻辑。例如: ```java @Aspect @Component public class CustomAspect { @Before("@annotation(customAnnotation)") // 拦截带有CustomAnnotation注解的方法 public void beforeMethod(CustomAnnotation customAnnotation) { // 在方法执行前执行的逻辑 } } ``` 3. 配置Spring AOP。在Spring配置文件中添加AOP的配置,例如使用`<aop:aspectj-autoproxy>`标签开启自动代理,并指定切面类的包名,让Spring能够自动扫描并应用切面逻辑。 4. 在目标方法上使用自定义注解。在需要切入的方法上标记使用自定义注解,例如: ```java @CustomAnnotation public void doSomething() { // 方法的实际逻辑 } ``` 这样,在调用`doSomething()`方法时,Spring AOP会拦截到带有`@CustomAnnotation`注解的方法,并执行切面逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值