Java 注入的Springbean在Spring引导应用程序中为空
我正在使用SpringBoot(1.5.3)开发RESTWeb服务。为了对传入的请求采取一些操作,我添加了一个拦截器,如下所示Java 注入的Springbean在Spring引导应用程序中为空,java,spring,spring-boot,dependency-injection,autowired,Java,Spring,Spring Boot,Dependency Injection,Autowired,我正在使用SpringBoot(1.5.3)开发RESTWeb服务。为了对传入的请求采取一些操作,我添加了一个拦截器,如下所示 @Component public class RequestInterceptor extends HandlerInterceptorAdapter { @Autowired RequestParser requestParser; @Override public boolean preHandle(HttpServletRequest request, H
@Component
public class RequestInterceptor extends HandlerInterceptorAdapter {
@Autowired
RequestParser requestParser;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
//HandlerMethod handlerMethod = (HandlerMethod) handler;
requestParser.parse(request);
return true;
}
}
RequestInterceptor
有一个自动连接的springbeanRequestParser
负责解析请求
@Component
public class RequestParserDefault implements RequestParser {
@Override
public void parse(HttpServletRequest request) {
System.out.println("Parsing incomeing request");
}
}
拦截器注册
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RequestInterceptor()).addPathPatterns("/usermanagement/v1/**");
}
}
还有我的Spring Boot应用程序
@SpringBootApplication
public class SpringBootApp {
public static void main(String[] args) {
SpringApplication.run(SpringBootApp.class, args);
}
}
现在,当一个请求进入时,它将进入
RequestInterceptor
的preHandle
方法,但RequestParser
为空。如果我从RequestParser
中删除@Component
注释,我在Spring上下文初始化过程中会遇到一个错误,没有找到RequestParser类型的bean。这意味着RequestParser
在Spring上下文中注册为Springbean,但是为什么在注入时它是空的呢?有什么建议吗 您的问题在于这个新的RequestInterceptor()
。
重写WebMvcConfig以注入它,例如:
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Autowired
private RequestInterceptor requestInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(requestInterceptor)
.addPathPatterns("/usermanagement/v1/**");
}
}
可能需要对RequestParserDefault
所在的包进行@ComponentScan
。@IndraBasak我相信它能够找到并注册该bean,因为如果我从中删除@Component
注释,在上下文初始化过程中会出现错误。您注册了HandlerInterceptorAdapter
使用WebMVCConfigureAdapter
?当您使用new创建一个类时,它不再是一个Springbean。它变成了普通的课堂。这就是为什么没有注入磁场。您可以将bean注入WebMvcConfig,并使用它,因为您要自己实例化beanRequestInterceptor
,您还必须创建RequestParserDefault
。e、 例如,registry.addInterceptor(新的RequestInterceptor(新的RequestParserDefault()).addPathPatterns(“/usermanagement/v1/**”)代码>谢谢兄弟,这很有帮助:)