启用 Hystrix 后 Autowire 不起作用

Posted

技术标签:

【中文标题】启用 Hystrix 后 Autowire 不起作用【英文标题】:Autowire doesn't work after enabling Hystrix 【发布时间】:2021-05-02 06:56:45 【问题描述】:

我遇到了一个问题,当我在我的微服务中添加 Hystrix(EnableHystrix) 时自动装配不起作用。

控制器类:

@RestController
@RequestMapping("/login")
@Slf4j
public class LoginController 

    @Autowired
    ILoginService loginService;


    @ApiOperation(value = "Validate user credentials", response = LoginUser.class)
    @PostMapping(value = "/validateCredentials")
    private ResponseEntity<LoginUser> validateUserCredentials(@RequestBody LoginUser logginUser) 
        LoginUser user=loginService.validateUser(logginUser);
         ......
         .....
   

ILoginService 的自动装配可以在没有 Hystrix 的情况下完美运行。

但是当我添加依赖时(版本 2.2.6 发布)

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
 </dependency>

并启用 Hystrix 为:

@EnableFeignClients("com.abcd")
@SpringBootApplication
@EnableHystrix
public class MyApplication

    public static void main(String[] args) 
        SpringApplication.run(MyApplication.class, args);
    


ILoginService 的 Autowire 失败并在尝试访问 autowired 属性时抛出 NullPointerException

我的这个配置在其他微服务中运行良好,但是在这个特定的微服务中失败了。这里出了什么问题?

编辑: StackTrace 是:

java.lang.NullPointerException
at com.demo.login.controller.LoginController.validateUserCredentials(LoginController.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)2021-01-28 17:09:12.999 DEBUG 1800 --- [nio-9200-exec-8] com.demo.login.ExceptionsHelper      : Exception: 

at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)

【问题讨论】:

【参考方案1】:

在目前的形式中,很难说到底发生了什么。 因此,我将提供一些可以导致解决方案的想法:

    你说,

ILoginService 的 Autowire 失败,尝试访问 autowired 属性时抛出 NullPointerException。

通常当它可以自动装配一个bean,因为它不存在或什么的时候,spring应该在启动过程中抛出一个异常,并且在启动过程中不可能“访问”自动装配的属性,因为系统不会启动,所以这很混乱。也许如果您可以提供堆栈跟踪以及您尝试访问该属性的位置,它可能会变得更加清晰......

    理论上可能(堆栈跟踪再次表明)有人试图在自动装配实际执行之前访问属性。从技术上讲,它是在春季通过 BeanPostProcessor 实现的,具有一定的优先级,可能会与其他 bean 后处理器竞争。

尝试重写控制器以使用构造函数注入(这样spring会在控制器的构造过程中注入ILoginService

@RestController
public class LoginController 
    // Note, no autowiring here
    private final ILoginService loginService;

    // If you are on old spring you need to mark this constructor with @Autowired,
    // in the recent spring versions its not required anymore as long as this is the only 
    // constructor of your class
    public LoginController(ILoginService loginService) 
       this.loginService = loginService;
    
    完成此操作后,尝试在构造函数中放置一个断点并查看注入的具体内容(在这种情况下,这是构造函数注入的优势)

【讨论】:

嗨,感谢您的回答。我已经编辑了我的问题以显示正在使用自动装配属性并添加了堆栈跟踪 我将其重写为构造函数注入并添加了一个断点。 LoginService 正确注入。但是NullPointerException仍然被抛出 好的,那么通过构造函数注入它可以工作了吗? 否,运行 validateUserCredentils 方法时会抛出相同的空指针异常 我假设,第 46 行是 `LoginUser user=loginService.validateUser(logginUser);` 在这种情况下,这没有意义 - 一旦创建控制器并注入数据字段,谁可以设置“空”呢?也许代码中的某些东西可以做到?将数据字段设为final,这样Java就不会在构造函数中设置值后更改该字段......现在会发生什么?

以上是关于启用 Hystrix 后 Autowire 不起作用的主要内容,如果未能解决你的问题,请参考以下文章

feign + hystrix 降级

Java类中的Grails @Autowire不起作用

Spring Autowire Hashmap 在 kotlin 中不起作用

如何启用 Hystrix DEBUG 级别的日志记录

如何在 zuul 启用 Hystrix 断路器?

Hystrix 默认超时不起作用