Monday, January 08, 2007

[Tech] Best-Practices for Spring Configurations

I've found an interesting article about Best-Practices for Spring configuration. More and more Java applications are based on the Spring framework. Over the time, software engineers develop their own best practices, but hardly anyone publishes them. Here are some suggestions described in the article:
  • Avoid using autowiring
  • Use naming conventions
  • Use shortcut forms
  • Prefer type over index for constructor argument matching
  • Reuse bean definitions, if possible
  • Prefer assembling bean definitions through ApplicationContext over imports
  • Use ids as bean identifiers
  • Use dependency-check at the development phase
  • Add a header comment to each configuration file
  • Communicate with team members for changes
  • Prefer setter injection over constructor injection
  • Do not abuse depencency injection
Certainly some software companies and developers have their own best practices, but the above mentioned one are general and should be used in every Spring based project.

Maybe our readers want to contribute their practices?

1 comment:

Alexander Schatten said...

I think particularly the last issue "Do not abuse dependency injection" is tricky, particularly for beginners. I found, that developers starting with Spring often have difficulties to detect, where to let Spring manage beans, and where "hard-wiring" in the application is the better strategy.

I really would like to get some opinions here.

I think one could make the choice by thinking of the time, when the wiring or configuration should be done and how often it changes.

E.g., it is rather unlikely that the "wiring" of domain objects will change at runtime, not even during test- and productive mode. This refactoring can be easily done with a modern IDE.

But it is rather likely that the DAO or the database, cache configuration changes between testing and production mode (just to give one example).

Moreover one might want to distinguish between lifecycle management and configuration: I find Spring handy to configure objects, and I meanwhile often do not need "own" implemented configuration classes, allthough this has not necessarily to do with lifecycle management capabilities of Spring.

Sometimes I even use Spring to fill test-object graphs for unit-tests (this is actually a usage as "persistence" mechanism). This might be an abuse though, and I am not sure, whether this could count as "best practice" ;-)