java`NativeWebRequest`在Spring Boot的传入请求中为空
我安装了一个Spring引导服务器,它可以成功地接收请求。它是使用OpenAPI
来生成端点定义的,用于处理参数转换
现在,我的问题是,我现在想检查不属于请求参数的头,而只是作为请求一部分的头
在我设置的另一个Spring Boot应用程序中,我通过添加控制器实现了这一点
@Autowired
NativeWebRequest request;
允许访问传入的请求
然而,在我当前的应用程序中,这始终是null
,我无法获取任何头数据。我怀疑我在SpringBoot应用程序设置中做了一些错误的事情
// Athena pulled in KeycloakAutoConfiguration when KeycloakAuthorization was added. However, the class
// is not part of the Athena application - so exclude by name since we cannot reference the class here.
@EnableAutoConfiguration(
excludeName = { "org.keycloak.adapters.springboot.KeycloakAutoConfiguration"},
exclude = {
DataSourceAutoConfiguration.class,
ErrorMvcAutoConfiguration.class,
HttpEncodingAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class,
ThymeleafAutoConfiguration.class,
WebSocketMessagingAutoConfiguration.class,
OAuth2ClientAutoConfiguration.class,
})
@SpringBootConfiguration
public class AthenaApplication extends SpringBootServletInitializer
# 1 楼答案
NativeWebRequest
bean应该从Spring 2.5.2开始提供。在我的示例中,我将它作为控制器的构造函数参数。Spring将在控制器bean创建时为其注入一个代理。每个收到的HTTP请求都会更新具体的实例值# 2 楼答案
在Spring应用程序中,在Bean中注入请求并不常见
而是向请求处理程序方法添加一个参数。有不同的支持类型和注释来访问请求头。例如:
见"Spring Framework Documentation"部分"Web Servlet"章节Method Arguments"
你写道:
在这个字段中有一个
@Autowired
注释。如果Spring无法自动连接它,它通常会引发异常,因此请仔细检查该类的实例是否是由Spring创建的,而不是意外地使用正常的new