I want to have inject a bean based on a String parameter passed from client.
public interface Report {
generateFile();
}
public class ExcelReport extends Report {
//implementation for generateFile
}
public class CSVReport extends Report {
//implementation for generateFile
}
class MyController{
Report report;
public HttpResponse getReport() {
}
}
I want report instance to be injected based on the parameter passed. Any help would be greatly appretiated. Thanks in advance
Use Factory method pattern:
The report type
enumcan be created by Spring when you call your controller with?type=CSV:However
ReportFactoryis pretty clumsy and requires modification every time you add new report type. If the report types list if fixed it is fine. But if you plan to add more and more types, this is a more robust implementation:With this implementation adding new report type is as simple as adding new bean implementing
Reportand a newReportTypeenum value. You could get away without theenumand using strings (maybe even bean names), however I found strongly typing beneficial.Last thought:
Reportname is a bit unfortunate.Reportclass represents (stateless?) encapsulation of some logic (Strategy pattern), whereas the name suggests it encapsulates value (data). I would suggestReportGeneratoror such.