java – 有条件地注入bean

前端之家收集整理的这篇文章主要介绍了java – 有条件地注入bean前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想根据从客户端传递的String参数注入一个bean.
  1. public interface Report {
  2. generateFile();
  3. }
  4.  
  5. public class ExcelReport extends Report {
  6. //implementation for generateFile
  7. }
  8.  
  9. public class CSVReport extends Report {
  10. //implementation for generateFile
  11. }
  12.  
  13. class MyController{
  14. Report report;
  15. public HttpResponse getReport() {
  16. }
  17. }

我希望根据传递的参数注入报表实例.任何帮助都会非常有用.提前致谢

解决方法

使用 Factory method模式:
  1. public enum ReportType {EXCEL,CSV};
  2.  
  3. @Service
  4. public class ReportFactory {
  5.  
  6. @Resource
  7. private ExcelReport excelReport;
  8.  
  9. @Resource
  10. private CSVReport csvReport
  11.  
  12. public Report forType(ReportType type) {
  13. switch(type) {
  14. case EXCEL: return excelReport;
  15. case CSV: return csvReport;
  16. default:
  17. throw new IllegalArgumentException(type);
  18. }
  19. }
  20. }

当您使用?type = CSV调用控制器时,Spring可以创建报告类型枚举:

  1. class MyController{
  2.  
  3. @Resource
  4. private ReportFactory reportFactory;
  5.  
  6. public HttpResponse getReport(@RequestParam("type") ReportType type){
  7. reportFactory.forType(type);
  8. }
  9.  
  10. }

但是,ReportFactory非常笨拙,每次添加新报表类型时都需要修改.如果报告类型列表如果修复则没问题.但是如果您计划添加越来越多的类型,这是一个更强大的实现:

  1. public interface Report {
  2. void generateFile();
  3. boolean supports(ReportType type);
  4. }
  5.  
  6. public class ExcelReport extends Report {
  7. publiv boolean support(ReportType type) {
  8. return type == ReportType.EXCEL;
  9. }
  10. //...
  11. }
  12.  
  13. @Service
  14. public class ReportFactory {
  15.  
  16. @Resource
  17. private List<Report> reports;
  18.  
  19. public Report forType(ReportType type) {
  20. for(Report report: reports) {
  21. if(report.supports(type)) {
  22. return report;
  23. }
  24. }
  25. throw new IllegalArgumentException("Unsupported type: " + type);
  26. }
  27. }

通过此实现,添加新报告类型就像添加新bean实现Report和新的ReportType枚举值一样简单.你可以在没有枚举和使用字符串(甚至可能是bean名称)的情况下离开,但是我发现强类型很有用.

最后想到:报告名称有点不幸.报告类表示(无状态?)某些逻辑(Strategy模式)的封装,而名称表明它封装了值(数据).我会建议ReportGenerator等.

猜你在找的Java相关文章