Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with doing Dependency Injection configuration in code?

XML seems to be the language of the day, but it's not type safe (without an external tool to detect problems) and you end up doing logic in XML. Why not just do it in the same language as the rest of the project. If it's java you could just build a config jar and put it on the classpath.

I must be missing something deep.

like image 837
Allain Lalonde Avatar asked Aug 18 '09 16:08

Allain Lalonde


3 Answers

The main downside to configuration DI in code is that you force a recompilation in order to change your configuration. By using external files, reconfiguring becomes a runtime change. XML files also provide extra separation between your code and configuration, which many people value highly.

This can make it easier for testing, maintainability, updating on remote systems, etc. However, with many languages, you can use dynamic loading of the code in question and avoid some of the downsides, in which case the advantages diminish.

like image 61
Reed Copsey Avatar answered Oct 22 '22 15:10

Reed Copsey


Martin Fowler covered this decision pretty well here:

http://martinfowler.com/articles/injection.html

Avoiding the urge to plagiarize... just go read the section "Code or configuration files".

like image 4
richardtallent Avatar answered Oct 22 '22 15:10

richardtallent


There's nothing intrinsically wrong with doing the configuration in code, it's just that the tendency is to use XML to provide some separation.

There's a widespread belief that somehow having your configuration in XML protects you from having to rebuild after a change. The reality in my experience is that you need to repackage and redeploy the application to deliver the changed XML files (in the case of web development anyway), so you could just as easily change some Java "configuration" files instead. Yo could just drop the XML files onto the web server and refresh, but in the environment I work, audit would have a fit if we did.

The main thing that using XML configuration achieves in my opinion is forcing developers to think about dependency injection and separation of concerns. in Spring (amongst others), it also provides a convenient hook to hang your AOP proxies and suchlike. Both of these can be achieved in Java configuration, it is just less obvious where the lines are drawn and the tendency may be to reintroduce direct dependencies and spaghetti code.

For information, there is a Spring project to allow you to do the configuration in code.

The Spring Java Configuration project (JavaConfig for short) provides a type-safe, pure-Java option for configuring the Spring IoC container. While XML is a widely-used configuration approach, Spring's versatility and metadata-based internal handling of bean definitions means alternatives to XML config are easy to implement.

like image 2
Rich Seller Avatar answered Oct 22 '22 14:10

Rich Seller