So, I just finished reading this blog post about Spring configuration advocating static getInstance() methods in some places in your code to reduce the amount of Spring xml config. Since I posted a reply on that blog, and the author would probably be inclined to moderate my entry and delete it because I directly oppose his position, I’ve reposted it here for the benefit of others to read.

THAT POST ADVOCATES POOR ARCHITECTURE. IGNORE IT.

If you’re relatively new to the Spring framework, ignore the recommendations in that post entirely – you’ll be saving yourself a _lot_ of pain in your software architecture.

Basically, here’s my reply:

This is a really bad idea and is exactly what Spring pojo-based Dependency Injection was created to avoid – to replace the Service Locator pattern. What you’re providing in a static getInstance() call is essentially a type-specific Service Locator.

Statics are evil – they’re inherently non-OO and usually encourage poor programming practices, especially the proliferation of unnecessary functional programming in an OO language. They should only be used to overcome poor programming situations outside of your control – i.e. a tool to use in an extremely limited basis only when you can’t use something else.

And although what you describe might make your life easier in the immediate sense, it significantly complicates it in other ways. How, for example, would you unit test your code properly without introducing dependencies not required for the test? Cleaner instance-level DI allows you do do things such as creating mock objects and anonymous inner classes for testing that is not possible with static singletons or where you would have to change a lot of code.

If you want to make your life easy, use autowiring – that’s exactly why it was created. The new Spring 2.0 XML namespaces also simplify things greatly, reducing XML config. And, with IDEs like Eclipse and IntelliJ IDEA that actually can traverse, manage, and refactor the XML spring files for you, the “XML Hell” argument for using Static singletons, especially when your own code suffers greatly in flexibility, is not really an issue.

Bottom line – never let laziness dictate your software architecture (especially when similar alternatives like autowiring exist), and stick with the pragmatic, well-thought and proven truly Object-Oriented solution.

I just thought it important to raise the issue on this for anybody reading this blog entry, especially those relatively new to Spring. What is mentioned is _not_ a good idea for 99% of cases, and the less-experienced Spring folks shouldn’t be led down a dangerous path. It could introduce really bad habits that would hurt you later on.