Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am debugging my Java Spring service and I get an @Autowired variable as null, when it shouldn't be.

Since I have declared the service's class as @Service, I want to double-check that my bean was scanned by Spring and included in the Application Context.

Therefore, I want to be able to observe in Eclipse the contents of the Application Context.

How is this possible?

like image 552
Yiannis Tsimalis Avatar asked Feb 11 '16 20:02

Yiannis Tsimalis


4 Answers

inject ApplicationContext into a bean that you can debug and call #getBeanDefinitionNames

like image 196
hahn Avatar answered Oct 13 '22 20:10

hahn


you can use log4j.jar to output all the WARNINGS, DEBUGS, INFO once you start your server. Follow the below link http://www.tutorialspoint.com/spring/logging_with_log4j.htm. I have a working example at my other laptop, can post the code. Let me know if you need it

like image 37
user3509208 Avatar answered Oct 13 '22 20:10

user3509208


I am not sure if this is the best way but without adding any extra framework,if you just want to check if dependencies are injected correctly or not ,you can firstly remove @Autowired annotation from the fields.

Now create a parameterized constructor and annotate the constructor with @Autowired. Spring will try to inject all the beans through the constructor.

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

Now you can put breakpoint inside the constructor to check what value is getting injected.

Hope this helps.

like image 24
Abhishek Garg Avatar answered Oct 13 '22 20:10

Abhishek Garg


There is a workaround to get the WebApplicationContext in the debugger without changing the source code.

The RequestContextUtils#findWebApplicationContext method will help us with this.

You need to pass the current request to it, which can also be obtained using the static method:

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

By combining these calls, you can get the context anywhere in the web application in the debugger and call any of its methods:

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

Slightly prettier version:

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
WebApplicationContext webApplicationContext = RequestContextUtils.findWebApplicationContext(request);
webApplicationContext.getBeanDefinitionNames();
like image 41
vszholobov Avatar answered Oct 13 '22 21:10

vszholobov