网络感知范围的组件不会在应用程序初始化期间创建

Component of web-aware scopes are not created during app initialization

我正在使用 springBootVersion = '2.5.4' 并尝试自动装配以下组件:

@Component
@RequestScope
public class TokenDecodingService {
   
   @Autowired
   HttpServletRequest httpServletRequest;
/* Some logic with request */
}

进入我的控制器

@RestController
@Slf4j
//@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class DrupalEnhancedController {

    @Autowired
    TokenDecodingService tokenDecodingService;

    ....

}

在调试过程中,我看到出现 No Scope registered for scope name 'request' 异常。每个网络感知范围都存在同样的问题。

首先,我认为我使用了错误的应用程序上下文,但我发现我使用的是 AnnotationConfigReactiveWebServerApplicationContext,并且此上下文应该接受 beans/components 的网络感知范围。

我还尝试在这样的 bean 中定义此逻辑:

    @Bean
    @RequestScope
    public TokenDecodingService tokenDecodingService() {
        return new TokenDecodingService();
    }

并尝试手动定义上下文侦听器:

@Bean 
public RequestContextListener requestContextListener(){
    return new RequestContextListener();
}

但不幸的是,我并没有取得任何进展。 我认为这里的根本原因是缺少网络感知上下文,那么如何启用它们?

您提到了 AnnotationConfigReactiveWebServerApplicationContext,所以我假设您有一个响应式 Web 应用程序。在反应式应用程序中没有“请求范围”甚至 HttpServletRequest 这样的东西,因为在一般情况下,这种应用程序不是基于 servlet 的。

您可能希望将反应式 ServerHttpRequest 注入到您的控制器方法中:

@RestController
public class DrupalEnhancedController {

    @GetMapping("/someurl")
    public Mono<SomeResponse> get(ServerHttpRequest request) { ... }
}