一.需要编写文件
注:该切面主要用于实现场景:方法A在执行中可能会报错,但无论方法是否执行成功都需要将请求入库,该切面便是用于实现该功能
(1)Warehousing.java
用于定义注解作用于何时何地
package com.example.springdemo.aop;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME) //作用于运行时
@Target({ElementType.METHOD}) //作用于方法
@Documented
public @interface Warehousing {
/**
* 描述信息
*
* @return
*/
String description() default "";
}
(2)WarehousingService.java
用于定义切入点以及在切入点前后需要实现功能
package com.example.springdemo.aop;
import com.example.springdemo.demo.WarehousingService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
@Aspect
@Slf4j
public class WarehousingAspect {
@Autowired
private WarehousingService warehousingService;
/** 自定义 @Warehousing 注解为切入点 */
@Pointcut("@annotation(com.example.springdemo.aop.Warehousing)")
public void warehousing() {}
/**
* 在切入点之前切入
*
* @param joinPoint
* @throws Throwable
*/
@Before("warehousing()")
public void doBefore(JoinPoint joinPoint){
/** 方法执行前将请求入库 **/
warehousingService.startInsert(joinPoint);
}
/**
* 在切点返回内容后处理
*
* @param joinPoint
* @throws Throwable
*/
@AfterReturning(value = "warehousing()",returning = "rvt")
public void doAfterReturning(JoinPoint joinPoint, Object rvt){
/** 更新任务信息 **/
warehousingService.endInsert(joinPoint, rvt);
}
}
(3)WarehousingAspect.java
用于编写具体功能实现代码
package com.example.springdemo.demo;
import com.example.springdemo.entity.DetailModelAi;
import com.example.springdemo.entity.RequestVO;
import com.example.springdemo.mapper.DetailModelAiMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import javax.annotation.Resource;
@Service
@Slf4j
public class WarehousingService {
@Resource
DetailModelAiMapper detailModelAiMapper;
/**
* 开始入库
* @param joinPoint
*/
public void startInsert(JoinPoint joinPoint) {
//获取请求中信息
RequestVO requestVO = (RequestVO)joinPoint.getArgs()[0];
if (!ObjectUtils.isEmpty(requestVO)) {
DetailModelAi detailModelAi = new DetailModelAi();
detailModelAi.setId(requestVO.getProvinceId());
detailModelAi.setName(requestVO.getProvinceName());
//执行入库操作
Integer verification=detailModelAiMapper.insert(detailModelAi);
if (verification<=0){
log.info("errorMsg:{}","请求入库失败");
}else {
log.info("message:{}","请求入库成功");
}
}else{
log.info("message:{}","入参为空");
}
}
/**
* 结束入库
* @param joinPoint
*/
public void endInsert(JoinPoint joinPoint, Object rvt) {
//类比startInsert()
}
}
二.切面使用
最后只需要在方法上加上@Warehousing便可实现该切面功能