繁体   English   中英

如何在运行时观察应用程序上下文(调试时)

[英]How to observe the Application Context at runtime (while debugging)

我正在调试我的 Java Spring 服务,我得到一个 @Autowired 变量作为 null,但它不应该是。

由于我已将服务的 class 声明为 @Service,因此我想再次检查我的 bean 是否已被 Spring 扫描并包含在应用程序上下文中。

因此,我希望能够在 Eclipse 中观察 Application Context 的内容。

这怎么可能?

ApplicationContext注入可以调试的bean并调用#getBeanDefinitionNames

一旦启动服务器,就可以使用log4j.jar输出所有警告,调试,信息。 请访问以下链接http://www.tutorialspoint.com/spring/logging_with_log4j.htm 我在其他笔记本电脑上有一个工作示例,可以发布代码。 如果您需要,请告诉我

我不确定这是否是最好的方法,但没有添加任何额外的框架,如果你只想检查依赖关系是否正确注入,你可以先从字段中删除@Autowired注释。

现在创建一个参数化构造函数并使用@Autowired注释构造函数。 Spring将尝试通过构造函数注入所有bean。

http://www.tutorialspoint.com/spring/spring_autowired_annotation.htm

现在你可以在构造函数中放置断点来检查注入的值。

希望这可以帮助。

有一种解决方法可以在不更改源代码的情况下在调试器中获取WebApplicationContext

RequestContextUtils#findWebApplicationContext方法将帮助我们解决这个问题。

您需要将当前请求传递给它,也可以使用 static 方法获得:

((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()

通过组合这些调用,您可以在调试器中的 web 应用程序中的任何位置获取上下文并调用其任何方法:

RequestContextUtils
    .findWebApplicationContext(((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest())
    .getBeanDefinitionNames();

稍微漂亮一点的版本:

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
WebApplicationContext webApplicationContext = RequestContextUtils.findWebApplicationContext(request);
webApplicationContext.getBeanDefinitionNames();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM