Simply marking a field as @Autowired
in a GWT servlet does not work as intended. The code will compile and the web application will start up - which means Spring was successfully able to autowire the field, but when the servlet is actually hit by client-side code, it will yield a NullPointerException
- like there's a different, uninitialized copy of the servlet being hit.
I've found several ways on the web to get this working, one is by using a base servlet class that does some Spring logic but doing this means every GWT servlet must extend this base class. The other way was by using AspectJ and the @Configurable
Spring annotation. There was very little configuration involved here and it just magically worked.
My question is why doesn't just autowiring the field just work as intended? What is GWT doing that causes this to break.
It turns out that when using Spring at least, there's a MUCH simpler way to do this such that you can use @Autowired and it doesn't involve massive configuration or base classes. The caveat is that you must also use AspectJ. Here's what you need for your GWT servlet:
And in your Spring config make sure you also have:
One final note. If you are also using Spring security with your GWT application (and in your GWT servlets), you will need to make sure you define the correct mode to ensure the AspectJ weaving is done correctly (i.e., you get both @Secured annotation processing AND the @Autowired processing) you will need: