Thursday, March 5, 2009

The joy of Spring!

Had the opportunity to Springify a co-workers project while he was on leave the other day. It already sort-of used Spring, but he had inverted the inversion-of-control (yeah... think about it, passing the context everywhere and getting single beans out, scary) and because of the architecture we were variously running into "got minus one from read call" errors (Database-side connections exhausted) or "No ManagedConnections available within configured blocking timeout" (JBoss Connection pool exhausted) depending on whether you used his oracle config (multiple connection pools with max-size of 100) or mine (max-size 10 per pool).

So! Time to throw out cruft, delete code and do proper dependency-injection! always great fun. I once did a project where most of the risk was in the business algorithm, but the data requirements started fairly simple. So I rolled my own database layer and got going. Later in the project the data requirements started to grow, transaction demarcation and correct handling became an issue so I took the time to Spring-ify it, and the joy of going from raw JDBC sql to JdbcTemplates and Hibernate HQL was huge! dozens of lines of verbose JDBC try-catch-finally evaporated to one-liners. just great!

I do love taking well-written OO code and re-wiring it with Spring, you can throw out huge amounts of code and eliminate bugs that you might have never known about! Connection pooling issues, correct rollbacks, host of junk like that. A lot of the ugly casting and boilerplate code just evaporates, and you're left with get-setters (which is another issue entirely, we should have properties!)

At the moment I tend to use a Builder pattern to boot-strap Spring from the init code (not a full spring stack yet...) and get a handle to a Spring bean configured with all the resources (it knows how to orchestrate the DAOs and usually contains most of the bus. logic) which then takes over processing. I could probably do better, but it works pretty well for the moment and is easy enough to unit test, so I'm happy.

No comments: