【问题标题】:Injected Spring Bean is NULL in Spring Boot Application在 Spring Boot 应用程序中注入的 Spring Bean 为 NULL
【发布时间】:2018-03-08 10:50:00
【问题描述】:

我正在使用 Spring Boot(1.5.3) 开发 REST Web 服务。为了对传入的请求采取一些措施,我添加了一个如下所示的拦截器。

@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 有一个自动装配的 Spring Bean RequestParser 负责解析请求。

@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);

}
}

现在当一个请求进来时,它会到达RequestInterceptorpreHandle 方法,但RequestParser 是NULL。如果我从RequestParser 中删除@Component 注释,我会在Spring 上下文初始化No bean found of type RequestParser 期间收到错误消息。这意味着RequestParser 在 Spring 上下文中注册为 Spring bean,但为什么它在注入时为 NULL?有什么建议?

【问题讨论】:

  • 可能需要RequestParserDefault所在包的@ComponentScan
  • @IndraBasak 我相信它能够找到并注册 bean,因为如果我从中删除 @Component 注释,我会在上下文初始化期间收到错误。
  • 您在WebMvcConfigurerAdapter注册HandlerInterceptorAdapter了吗?
  • 当您使用 new 创建一个类时:new RequestInterceptor(),它不再是一个 Spring bean。变成了普通的课。这就是为什么不注入该字段的原因。您可以将 bean 注入到 WebMvcConfig,并使用它
  • 由于您是自己实例化 bean RequestInterceptor,因此您也必须创建 RequestParserDefault。例如,registry.addInterceptor(new RequestInterceptor(new RequestParserDefault())).addPathPatterns("/usermanagement/v1/**");

标签: java spring spring-boot dependency-injection autowired


【解决方案1】:

你的问题在于这个new RequestInterceptor()。 重写您的 WebMvcConfig 以注入它,例如像这样:

@Configuration  
public class WebMvcConfig extends WebMvcConfigurerAdapter  {  

  @Autowired
  private RequestInterceptor requestInterceptor;

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(requestInterceptor)
            .addPathPatterns("/usermanagement/v1/**");
  }
} 

【讨论】:

  • 谢谢兄弟帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多