首页 > 解决方案 > 具有方面注释方法时的Spring Autowired空字段

问题描述

我正在开发一个 Spring Web 应用程序。我根本没有 XML 配置。Spring Boot 应用程序的主类是带有组件扫描的注释,其中包括此处列出的所有 bean。

拥有这个控制器类:

@CrossOrigin
@RestController
@RequestMapping(value = "/documento/detail/tabs")
public class InfoController {

@Autowired
private DocDetailService detailService;

/**
 * SEC 26-28: Pricing e posizioni
 */
@LogMethod
@GetMapping(value = "/pricing/{numOperazione}", produces = MediaType.APPLICATION_JSON_VALUE)
private ResponseEntity<DetailPricingDTO> getDettagliPricingEPosizioni(
        @PathVariable(value = "numOperazione") final String numOperazione) throws DocumentNotFoundException {
    return ResponseEntity.ok(detailService.getDettagliPricing(numOperazione));
}

@LogMethod 定义如下:

@Documented
@Retention(RUNTIME)
@Target({ METHOD })
public @interface LogMethod {

}

使用如下定义的方面,记录使用该请求注释的所有方法

@Aspect
@Component
@Scope("singleton")
public class LogEventAspect {

private final Logger log = LoggerFactory.getLogger(this.getClass());

@PostConstruct
public void postConstruct() {
    log.info("# LogMethod annotation ASPECT is enabled #");
}

@Pointcut("@annotation(LogMethod)")
public void logEventAnnotationPointCut() {
    // Method is empty as this is just a point-cut, the implementations are in the
    // advises.
}

@AfterThrowing(pointcut = "logEventAnnotationPointCut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
    log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'",
            joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(),
            e.getCause() != null ? e.getCause() : "NULL", e.getMessage(), e);
}


@Around("logEventAnnotationPointCut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {

    // Log before execution
    if (log.isDebugEnabled()) {
        log.debug("Enter>>>: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
    }

    Object result = joinPoint.proceed();

    // log after execution
    if (log.isDebugEnabled()) {
        log.debug("Exit<<<: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), result);
    }

    return result;

}

}

控制器中的 detailService 为 NULL。如果我删除 @LogMethod 服务已正确初始化。
此外,如果我在@Service 类中使用@LogMethod 而不是@RestController,则其他bean 的自动装配确实有效。为什么会这样?

标签: javaspringinversion-of-controlaopautowired

解决方案


推荐阅读