I guess it’s time for the solution of the first Spring Puzzler. I’ve received a total of 79 votes, 35% got it right.
The solution was: Bienvenido a Spring Puzzlers Sergi.
In case you want to download the code, you can find it here: https://github.com/salmar/SpringPuzzlers
The first thing to notice is that SpanishWelcomePrinter was not annotated, that means the component scan will never pick it up and there won’t be any SpanishWelcomePrinter in the Application Context. Only one implementation of LocalizedWelcomePrinter will exist, the EnglishWelcomePrinter.
We can now safely discard the NoSuchBeanDefinitionException. But this was not the trap…even if we had the @Named in the SpanishWelcomePrinter, we would have gotten the same output.
The catch was in the ConsoleWelcomeService where we try to inject a static field. Static fields are omitted for dependency injection, in our case we are going to stick with SpanishWelcomePrinter, instantiated with the new operator and no DI will happen. We can discard the possibility to get the message in English now. NullPointerException cannot happen at any point…
The next Spring Puzzler will be published the 13th Oct.