I'm developing a Web application using Spring.
I have a common abstract class and many implementions of it.
Now, in a controller, depending on some parameter, I need different implementations of it.
This can be easily implemented with Factory Pattern.
For example:
abstract class Animal{
public abstract void run(){
}
}
class Dog extends Animal{
...
}
Class Cat extends Animal{
...
}
Now with factory pattern, I can create a factory class with a factory method which creates Animals based on some parameter. But I don't want to create instances on my own.
I need the same functionality, but I want Spring to manage everything. Because different implementations have their dependencies and I want them to be injected by Spring.
What is the best way of handling this situation?
Configure the beans you want to be created as prototype beans. Next create a factory which basically knows which bean to retrieve from the application context based on the input (so instead of creating them you basically let spring do the heavy lifting).
Defining the components can be done with either @Component
combinded with @Scope("prototype")
or by using XML configuration.
abstract class Animal{
public abstract void run(){}
}
@Component
@Scope("prototype")
class Dog extends Animal{}
@Component
@Scope("prototype")
Class Cat extends Animal{}
And an AnimalFactory
to complete the answer.
@Component
public class AnimalFactory implements BeanFactoryAware {
private BeanFactory factory;
public Animal create(String input) {
if ("cat".equals(input) ) {
return factory.getBean(Cat.class);
} else if ("dog".equals(input) ) {
return factory.getBean(Dog.class);
}
}
public void setBeanFactory(BeanFactory beanFactory) {
this.factory=beanFactory;
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments