【问题标题】:Component of web-aware scopes are not created during app initialization应用程序初始化期间未创建 Web 感知范围的组件
【发布时间】:2022-01-02 21:38:10
【问题描述】:

我正在使用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,并且此上下文应该接受 bean/组件的 Web 感知范围。

我也尝试在这样的 bean 中定义这个逻辑:

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

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

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

但不幸的是,我没有通过这种方式取得任何进展。 我认为这里的根本原因是缺少 Web 感知上下文,那么我该如何启用它们呢?

【问题讨论】:

    标签: java spring spring-boot spring-mvc web


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢,原来如此。它帮助我在我的应用程序 yaml 中删除 spring.main.web-application-type: reactive 并使用 spring-cloud-starter-netflix-zuul 而不是 spring cloud gateway。不幸的是,它不适用于 spring boot 2.5.2 版本,所以我不得不实现这里提到的解决方法 - github.com/spring-cloud/spring-cloud-netflix/issues/4008
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    • 1970-01-01
    • 2014-04-19
    • 2011-05-03
    • 2015-08-15
    相关资源
    最近更新 更多