This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Just have started reading Spring in Ation- Second Edition. So far have liked the book, DI pattern and Spring in general.
Many examples in the first few chapters describe how to let spring create and get objects (using getBean) for you instead of you having to do 'new'
These examples use predefined values stored in XML file.
But, most of the times objects are needed to use init values which are not known when .XML file is created.
for e.g. batch job that reads from flat file or Servlet program that reads from parameters or interactive
program that reads data from screen.
In these cases, are we first supposed to let Spring create object for us using values defined in .Xml file and then
manually call the set(Property) methods ? or there is any other way you can feed these values stored in local
variables, during object creation ?
I use the setter methods (or builder pattern if object is large) to create a VO/bean and then use that VO by passing to the bean method. So, I generally don't wire VO class as they can't be used as dependencies (they have no business behavior as such).
Please correct me If I'm missing or breaking any design principal here.
Without knowing the specifics of what you're trying to do, might I suggest creating an implementation of FactoryBean? It lets you get involved in the creation of your bean, but still be able to wire it up as a bean in Spring. Within the factory bean, you can set its properties to whatever you want. You might even consider setting those properties through constructor arguments and not providing setters to make them immutable. Really depends on what you're trying to do and what your need are.
There are other options, too. The Spring Expression Language can do runtime evaluation of an expression when setting properties. That expression could be written to call out to some object that looks up the info you won't know until runtime.
If you're using Spring 3.1, there is the new concept of property sources, where you can draw properties from a variety of sources (property files, servlet init parameters, etc) or even write your own extension of PropertySource to draw data from wherever you want. (In demos, I have a ChuckNorrisPropertySource that *always* returns "Roundhouse Kick" regardless of the property being asked for.)
You might even consider (if none of the above meet your needs) writing an Aspect (AspectJ, not Spring AOP) that intercepts the creation of your class and does injection at creation time. That's a bit heavy-handed, but it's a workable option. Something to keep in mind, anyway.
And there are probably other options that aren't coming directly to mind. These are just a few that I thought of right away.