Dependency Injection Is More Than Wiring Components
Dependency Injection is widely used nowadays. However, at least in the Java EE space this is narrowed down to "wiring components". I think configuring beans and injecting simple types is at least as important. The alternative is to read in configuration properties from files. Here is why I think DI is the much better approach for that:
- Every project with a certain complexity has this problem. It needs to be adjusted to different users, use cases etc. A common problem should have a standardized solution
- Reading in configuration files is not that easy. You have to handle exceptions if the file does not exist. You need to figure out what to do if a certain value is not set. You might want to have multiple files that can override configurations. I have to admit that I have seen projects in which the most complex code handled the configuration. Spring's XML configuration is already a powerful solution for this. And if you want to use properties files: The PropertyPlaceholderConfigurere allows to use those for configurations as well without writing any code. The PropertyPlaceholderConfigurere is very flexible - see its JavaDoc. But even if this is not enough: Using the BeanFactoryPostProcessor interface you can add your own configuration extensions.
- As configuration is needed almost anywhere the class handling the configuration file becomes a dependency for a lot of classes. This is not a good design. Using DI the configuration will be injected and there is no such dependency.
- Testing will also be hard if each class depends on the class handling the configuration. You will need a complete and correct configuration even for the smallest unit test. Otherwise the configuration cannot be read in. Changing the configuration for a specific test will either be impossible or the code for the configuration will become even more complex. Using the DI approach this is no problem as the configuration is injected and you can easily inject different values.
Of course this is not apparent during a short demo - but in real life DI for these kinds of applications it is a huge advantage.
Labels: Configuration, Dependency Injection, Spring
J for Java |
I for Internet, iMac, iPod and iPad |
Me for me