Spring is great. Those guys really know their Java onions. The only problem with Spring is that despite a load of really good API documentation, the actual real-world application of this framework is only gleaned by blood sweat and fear.
Some basic tips then to avoid some messy quagmires in the code:
- don’t go mad with chained config files. You will kick yourself when it comes to debugging during testing. No more than five should be sufficient
- in your test branch (assuming your are following a maven-like code structure) link in configuration files from the production branch THAT DO NOT NEED TO BE CHANGED FOR TESTING. This also saves you a sanitorium’s worth of palpitations. Sure, create config files that do give you specific testing conditions. There should not need to be too many, if any, of these.
- make your Spring Managed Beans (SMBs) stateless where possible. That means NOT declaring their scope as prototype. Leave the scope blank.
- inject as many dependencies as possible into your bean during the beans definition. Avoid injecting at runtime as this just adds to the pain.
- create bean parent definitions in your config files so that you don’t end up repeating the same definitions over and over and over and over …
- avoid gathering beans on the fly from the BeanFactory. Your blood pressure will drop dramatically as this reduces runtime issues and handily cleans up the code nicely.
- if you must gain a reference to a managed bean in your code at runtime, make sure that you use the BeanFactory that Spring magics up by implementing the BeanFactoryAware interface into your class and adding the method public void setBeanFactory(BeanFactory beanFactory) to set a local instance BeanFactory member. Don’t be clever and try to invent your own BeanFactory implementation. It will blow up in your face.
- don’t attempt to mess with the inner workings of Springs DI/IoC stuff. Its complicated and will only give you a nosebleed.
- Autowire if you must, but just be warned that you can come really quite unstuck at runtime because you have even less of an idea what Spring is doing than under the declarative bean wiring approach.
And campers, remember this. The boys that have spent years building Spring into what it is today have spent a lot more time agonising over and testing their work than you can ever hope to achieve in your app. If you have a problem with a Spring implementation, more often than not it will be down to something you have done with it/to it rather than a bug in the implementation itself. Google is your friend.
Someone quite obscure once said: “There isn’t something you are trying to do in Spring that someone hasn’t already done. The trick is to hunt down how THEY solved the problem.”