springAop+自定义注解

一、springAop小demo

1.首先导入依赖

<!-- springAOP切面开发的依赖  -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.3.6</version>
        </dependency>

2.需要开启springboot的动态代理

  • 启动类加上注解
@EnableAspectJAutoProxy

3.配置切面和切点以及通知

@Component
@Aspect
@Slf4j
public class LogAspect {
    
    

    // pointcut
    @Pointcut("execution(* com.idle.idlemanager.service.IdleManagerService.*(..))")
    public void pc(){
    
    }

    @Before("pc()")
    public String before(){
    
    
        System.out.println("前置");
        return "前置通知";
    }

    @After("pc()")
    public String after(){
    
    
        System.out.println("后置");
        return "后置通知";
    }
}

二、自定义注解

  • 定义注解
@Target({
    
    ElementType.TYPE,ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
    
    
    /**
     * 日志描述
     * 对于什么表格进行了什么操作
     */
    int description()  default 0;

    /**
     * 操作了的接口
     * @return
     */
    String  interfaceName() default "";
}

  • 使用注解
@Log(description = 4,interfaceName = "getUser")
    @GetMapping("user-by-name/{userName}")
    public ResultVo getUser(@PathVariable String userName){
    
    
        return userService.getUser(userName);
    }

三、使用AOP和注解实现日志记录

1.插入日志实体类

Data
@TableName("idle_log")
public class IdleLogEntity implements Serializable {
    
    
    /**
     *
     */
    @TableId(type = IdType.AUTO)
    private Integer id;
    /**
     * 描述
     */
    private Integer description;
    /**
     * 接口
     */
    private String interfaceName;
    /**
     * 操作管理员
     */
    private String managerName;
    /**
     * 操作时间
     */
    private String opeTime;
}

2.自定义注解

@Target({
    
    ElementType.TYPE,ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
    
    
    /**
     * 日志描述
     * 对于什么表格进行了什么操作
     */
    int description()  default 0;

    /**
     * 操作了的接口
     * @return
     */
    String  interfaceName() default "";
}

3.插入日志的service

  • service
@Service
@Slf4j
public class IdleLogServiceImpl implements IdleLogService {
    
    

    @Resource
    private IdleLogMapper logMapper;

    @Override
    public Integer addLog(IdleLogEntity entity) {
    
    
        try {
    
    
            if (entity == null){
    
    
                return 0;
            }
            int insert = logMapper.insert(entity);
            return insert;
        } catch (Exception e) {
    
    
            log.error("add log error : {}",e.getMessage());
            return 0;
        }
    }
}

4.编写切面

  • 使用后置通知
@Component
@Aspect
@Slf4j
public class LogAspect {
    
    

    @Autowired
    private LoginInterceptor login;

    @Autowired
    private IdleLogService logService;

    // pointcut
    @Pointcut("@annotation(com.idle.idlemanager.annotion.Log)")
    public void pc(){
    
    }

    @After("pc()")
    public void after(JoinPoint joinPoint){
    
    
        try {
    
    
            DataUtils dateUtils = new DataUtils();
            String userName = login.getManager().getUserName();
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            Log oprationLog = method.getAnnotation(Log.class);
            IdleLogEntity idleLogEntity = new IdleLogEntity();
            idleLogEntity.setDescription(oprationLog.description());
            idleLogEntity.setInterfaceName(oprationLog.interfaceName());
            idleLogEntity.setManagerName(login.getManager().getUserName());
            idleLogEntity.setOpeTime(dateUtils.getData());
            Integer integer = logService.addLog(idleLogEntity);
            return ;
        } catch (Exception e) {
    
    
            log.error("add log aspect error : {}",e.getMessage());
        }
    }
}

5.使用注解

@CrossOrigin
@RestController
public class IdleUserController {
    
    

    @Autowired
    private IdleUserService userService;

    private final static Logger logger = LoggerFactory.getLogger(IdleUserServiceImpl.class);

    @Log(description = 4,interfaceName = "listUser")
    @GetMapping("alluser")
    public ResultVo listUser(){
    
    
        return userService.listAllUser();
    }
}

猜你喜欢

转载自blog.csdn.net/Proxbj/article/details/123910599