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?
inject ApplicationContext
into a bean that you can debug and call #getBeanDefinitionNames
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
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With