手把手教学切面编程实战之Spring AOP基于注解实现

理论是实践的基础,实践是检验真理的唯一标准

一、快速入门指引(所见即所得)

  • Spring AOP核心概念

  • 在我们开始使用AOP之前,我们先熟悉AOP概念和术语。这些术语并非特定于Spring,而是与AOP相关。理解这些概念和术语非常有助于理解本文。

手把手教学切面编程实战之Spring AOP基于注解实现_第1张图片

  • 切面在项目中应用场景

手把手教学切面编程实战之Spring AOP基于注解实现_第2张图片

二、核心业务场景实战之 "记录业务操作行为"

  • 快速上手的核心步骤

  1. SpringBoot启动类开启AOP:@EnableAspectJAutoProxy(proxyTargetClass = true)
  2. 定义切面注解类:ArticleOperational
  3. 定义切面核心类:ArticleContentAspect
  4. 在核心业务中使用切面注解:@ArticleOperational(action = "取消置顶")
  • SpringBoot启动类开启Aop

package com.demo.content;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

/**
 * @author youyun.xu
 * @ClassName: ContentApplication
 * @Description: 內容管理微服务
 * @date 2020/7/23 上午09:00
 */
@SpringBootApplication(scanBasePackages = "com.demo")
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class ContentApplication {

    public static void main(String[] args) {
        SpringApplication.run(ContentApplication.class, args);
    }
}
  • 定义切面注解类

package com.demo.annotation;

import java.lang.annotation.*;

/**
 * @author youyun.xu
 * @ClassName: ArticleOperational
 * @Description: 切面管理文件操作注解
 * @date 2020/7/23 上午09:00
 */
@Target({ElementType.TYPE,ElementType.METHOD,ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ArticleOperational {

    String action() default "";
}
  • 定义切面核心类

package com.demo.aop;

import com.alibaba.fastjson.JSON;
import com.demo.annotation.ArticleOperational;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
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 javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author youyun.xu
 * @ClassName: ArticleContentAspect
 * @Description: 切面监控文章操作状态
 * @date 2020/7/23 上午09:00
 */
@Aspect
@Component
public class ArticleContentAspect{

    // 定义切入点
    @Pointcut("@annotation(com.tcl.uf.content.annotation.ArticleOperational)")
    public void operational() {}

    /**
     * 获取参数列表
     * @param joinPoint
     * @return
     * @throws ClassNotFoundException
     * @throws NoSuchMethodException
     */
    private static Map getFieldsName(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        ParameterNameDiscoverer pnd = new DefaultParameterNameDiscoverer();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String[] parameterNames = pnd.getParameterNames(method);
        Map paramMap = new HashMap();
        for (int i = 0; i < parameterNames.length; i++) {
            paramMap.put(parameterNames[i], args[i]);
        }
        return paramMap;
    }

    @AfterReturning(value = "operational()")
    public void p1(JoinPoint joinPoint){
        //HttpServletRequest 和 HttpServletResponse 对象(示例)
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();
        User user = getUserInfo(request);
        //获取请求参数和值(示例)
        Map params = getFieldsName(joinPoint);
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        //获取注解信息(示例)
        ArticleOperational articleOperational= method.getDeclaredAnnotation(ArticleOperational.class);
        //持久化操作日志
        saveArticleOperationalRecord(articleOperational.action(),user.getUserId(),JSON.toJSONString(params));
    }

    private void saveArticleOperationalRecord(String operational,String userId,String remarks){
        //持久化操作记录到数据库
    }

    private User getUserInfo(HttpServletRequest request){
        //我此处写的是伪代码、仅供参考
        return new User("youyun.xu","13246738031");
    }
}
  • 业务使用AOP切面注解

package com.demo.service.impl;

import com.demo.annotation.ArticleOperational;
import com.demo.service.ArticleContentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author youyun.xu
 * @ClassName: ArticleContentServiceImpl
 * @Description: 文章内容服务Service
 * @date 2020/7/23 上午09:00
 */
@Service("articleContentService")
public class ArticleContentServiceImpl implements ArticleContentService {

    private static final Logger log = LoggerFactory.getLogger(ArticleContentServiceImpl.class);

    @Override
    @Transactional(rollbackFor = Exception.class)
    @ArticleOperational(action = "取消置顶")
    public void cancelArticleTop(Long articleId) {
        //取消置顶业务核心代码
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @ArticleOperational(action = "删除文章")
    public void delete(List articleIds) {
        //删除文章业务核心代码
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @ArticleOperational(action = "文章下线")
    public void offline(List articleIds) {
        //文章下线业务核心代码
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @ArticleOperational(action = "文章发布")
    public void publish(List articleIds) {
        //文章发布业务核心代码
    }
}

在核心业务代码的函数上添加自定义注解  @ArticleOperational(action = "删除文章") 即可。

  • 小结

  1. 高效、灵活、对代码无任何侵入性
  2. 减少大量冗余代码、代码可读性更好
  3. 原创不易,你如果喜欢请给帮我反手点个赞。

人生不要怕做选择,因为选错才是必然的,选对才是偶然的。不要太多勉强,做自己喜欢做的事情,不要怕选错,而是提高选对的成功率。

你可能感兴趣的:(AOP切面编程,spring,java,aop,面向对象编程)