I have a question related to frameworks like Spring. We can create factory patterns and service locators in java and can achieve what spring is providing through defining beans in the xml file then why do we prefer XML config files over java?
We don't, necessarily--it depends on your needs. One advantage of Spring is that the hard work has already been done, whether or not you use XML for configuration.
I still use XML configuration a lot, though, particularly when I have to target multiple environments (which I frequently do) or if there's a lot of setup for deep, but still partial, integration tests.
Joined: Jul 01, 2003
Spring provides A way to compose application components but isn't necessarily THE way to do it. A lot depends on how dynamic your composition needs to be. Spring allows for XML based composition, which means changes can be made simply by restarting the application (and re-reading the XML file). Alternatively, configuration can be done in the Java code with annotations, but the changes don't take effect until re-compile. If you need changes in mid-run, then another approach will be required.
Also, the Spring framework offers much more than just DI. DI just happens to be one of the patterns for composing applications and isn't necessarily required in many cases.