Now we have five child class which extends ParentClass1. Now in spring when are composing MyClass1 ,how we will determine which child instance out of five needs to be injected here (as it depends upon some runtime parameter depending on which we have to create child instance like if i=1 instantiate child1, if i=2 instantiate child2). Please Guide me with brief example if there is any way to configure the configuration file i.e spring-config.xml and changes need to be done in MyClass1 to achieve above scenario ?
In the basics of xml, the config file is about static configuration of stuff you know up front.
For more dynamic runtime requirements you have some choices.
1) If you are using Spring 3.x there is the Spring Expression Language that you can use, but the dependency is still set once up front, so once you choice of the fve is determined that object will always reference the one that you choice.
2) If you are not using Spring 3.x and you still are ok with the dependency set up front once, you could use the PropertyPlaceholderConfigurer and create a .properties file with the value you want for that particular run. This is still a little bit static and needs to be known up front, but you are externalizing the choice from your xml.
3) If it is more dynamic where the dependency can change often, then you might go the approach of creating a Factory POJO class that has a factoryMethod that takes a parameter and based on that value the factory returns one of the five instances. Then define the Factory class as a bean and inject the factory into your class, and when you need a dependency then in code call the factory method passing in the value for your int i.
4) You could create a map as a bean with all five instances of the subclass in it with a key of your int i, then inject the map into your class and when you need your child class get it from the Map.
Thanks Mark I got much clarity from option 3 you described as i have worked on spring 2.0.My question is how we will pass the argument in factory method .Assuming this parameter is coming from some value user selected on user interface and not know while setting up config file. Below is My factory, client and configuration file
Below is the code snippet from config file
// i know we can provide constructor argument above but that will be static. This argument is supposed to come from value user selected on user interface
//Below is my client method
Now how i will pass the value of i from main method to factory method considering above example?