首页 > 解决方案 > Spring AOP 看不到方法

问题描述

在我的项目中,我有AspectService类,用于记录所有控制器方法:

@Component
@SLFJ
@Aspect
public class AspectService {
   @Pointcut("@annotation(com.aleksandr0412.bookstore.annotations.Audit) && execution(public * *(..))")
public void publicAspectAudit() {
}

@Around(value = "publicAspectAudit()")
public Object aspect(ProceedingJoinPoint joinPoint) throws Throwable {
    ObjectMapper om = new ObjectMapper();
    AuditMessage auditMessage = new AuditMessage();
    UUID uuid = UUID.randomUUID();
    auditMessage.setUuid(uuid);
    auditMessage.setAuditCode(((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(Audit.class).value());
    auditMessage.setEventCode(EventCode.START);
    auditMessage.setTimeStart(LocalDateTime.now());
    auditMessage.setUsername("");
    Object[] args = Arrays.stream(joinPoint.getArgs())
            .filter(arg -> !(arg instanceof UriComponentsBuilder)).toArray();
    auditMessage.setParams(om.writeValueAsString(args));

    log.info(auditMessage.toString());

//-----

我的项目有 3 个模块:第一个 - audit 和AspectService,第二个和第三个是具有不同控制器的可执行模块。我的问题是,在一个模块中,带有@Audit注释的公共控制器方法工作正常,但在另一个模块中,AspectService看不到它们。

工作真实:

 @Audit(AuditCode.AUTHOR_CREATE)
    @Override
    public ResponseEntity<AuthorDto> createAuthor(AuthorDto authorDto, UriComponentsBuilder componentsBuilder) {
        log.info("createAuthor with {} - start ", authorDto);
        AuthorDto result = service.addAuthor(authorDto);
        URI uri = componentsBuilder.path("/api/author/" + result.getId()).buildAndExpand(result).toUri();
        log.info("createAuthor end with {}, with result {}", authorDto, result);

        return ResponseEntity.created(uri).body(result);
    }

不起作用:

  @Audit(AuditCode.CREATE_USER)
    @Override
    public ResponseEntity<UserDTO> createUser(
            UserDTO userDTO,
            UriComponentsBuilder componentsBuilder
    ) {
        log.info("createUser with {} - start ", userDTO);
        if (userDTO == null) {
            throw new EmptyException();
        }
        UserDTO result = userService.add(userDTO);
        URI uri = componentsBuilder.path("/api/user/" + result.getId()).buildAndExpand(result).toUri();
        log.info("createUser end with result {}", result);
        return ResponseEntity.created(uri).body(result);
    }

当我尝试调试它时,在第二个示例中我不访问AspectService类。我在哪里犯错?

标签: javaspringspring-aop

解决方案


我将带有 AspectService 包的 @ComponentScan 添加到第二个模块。它解决了我的问题


推荐阅读