I am getting into Spring now and I have a question. Let’s assume we have an interface IControl and we have three implementations of it – e.g. Button, Label, Checkbox.
The user will enter a number N at runtime and I should create N controls of a specific type(Button, Label or Checkbox). The problem is I want this specific type to be configured before the program is run. For example I configure in my spring.xml that I want buttons, then the program is run, the user enters 10 and I create 10 buttons.
<beans>
<bean id="controlCreator" class="org.company.ControlCreator">
<property name="controlType" ref="?!?!?!?!?!?!"/>
</bean>
</beans>
How should I go configuring this?
P.S This is just a learning example I made up.
Best regards,
Petar
First of all, allow me to state that Spring is not intended to do this. Spring wants to an unintrusive method of wiring your components together. It’s not meant to be used for spawning objects at runtime.
The correct approach
The correct approach would be to design a factory class. You can set the defaults of this using Spring at startup, then ask the factory for instances at runtime.
The intrusive apporach
If you really want to use Spring, you can do intrusively by asking the applicationContext for an instance of your control.
By default, all Spring beans are singletons, but you can make them into prototypes.
Disclaimer: code not tested, but should be something like this:
Applicationcontext.xml
Code
The unintrusive approach
If you really want to use Spring, and you really want to use it unintrusively, you will have to use Method Injection. Inject a factory method into your class.
The code would be the following:
Applicationcontext.xml
Code
This will return the bean when the lookup method is called. Since the bean is prototype, it will create a new one.