我在选择应该注入的正确 spring bean 时遇到问题。我需要一种方法来告诉 spring 容器注入什么 bean,这取决于对前一个类的调用。我在 xml 中完成所有 spring bean 接线。
我的问题:这是否可能,如果它是对实现的任何参考?
我创建了一些示例代码来说明我想要完成的工作。随意更改它,以便在运行时根据所选的 reportType 注入正确的 ReportHeader bean。
public enum ReportType{
Credit,
Annul
}
public class ReportService {
private ReportHeaderService reportHeaderService;
private ReportType reportType;
public ReportService (){}
public setReportType(ReportType reportType){
this.reportType = reportType;
}
public void setReportHeaderService(ReportHeaderService reportHeaderService){
this.reportHeaderService = reportHeaderService;
}
private void generateHeader(){
//i would like to call my service like this and have the correct bean injected to ReportHeader.
reportHeaderService.generateHeader(reportType)
}
}
public class ReportHeaderService {
private ReportHeader reportHeader;
//this will call the injected bean that needs to be selected accoring to the ReportType
public void generateHeader(ReportType type){
reportHeader.createHeader();
}
}
public interface ReportHeader{
public void createHeader();
}
public class CreditReportHeader implements ReportHeader{
public void createHeader(){
..dostuff();
}
}
public class AnnulReportHeader implements ReportHeader{
public void createHeader(){
..dostuff();
}
}