代码之家  ›  专栏  ›  技术社区  ›  bibliophilsagar

在springboot中通过自动连接获得NullpointerException(奇怪的场景)

  •  1
  • bibliophilsagar  · 技术社区  · 7 年前

    我知道这个问题有很多答案,我也知道可能会发生这种情况的各种情况。

    但我想我错了,考虑到我的情况,我不知道所有可能的组合。 让我分享代码片段,这样代码就可以自己说话了。

    控制器类

    @RestController
    public class ReportController {
    
        @Autowired
        ReportFactory reportFactory;
    
        //RequestMapping goes here!
        public ResponseEntity<Report> getReport() {
    
            ReportGenerator<?> reportGenerator = reportFactory.getReportGenerator("order"); //line# 43
            return getSuccessResponse(reportGenerator.getReport(companyGUID, startDate, endDate)); //geting the exception here saying reportGenerator is null!
        }
    
        @SuppressWarnings({ "rawtypes", "unchecked" })
        private <T> ResponseEntity getSuccessResponse(T response) {
            return new ResponseEntity(response, HttpStatus.OK);
        }
    }
    

    我得到了 reportGenerator ReportFactory 正如你所看到的那样 自动连线 .

    ReportFactory.java

    @Component
    public class ReportFactory {
    
        @Autowired
        Map<String, ReportGenerator> reportList;
    
        public ReportGenerator<?> getReportGenerator(String reportType) {
    
            return reportList.get(reportType.toLowerCase());
        }
    } 
    

    正如你所看到的,这个类被注释为 Component 它还依赖于 reportList

    ReportGeneratorConfig.java

     @Configuration
        public class ReportGeneratorConfig {
    
            @Autowired
            BeanFactory factory;
    
            @Bean
            public Map<String, ReportGenerator> reportList() {
    
                HashMap<String, ReportGenerator> reportList = new HashMap<String, ReportGenerator>();
                reportList.put("order", factory.getBean(OrderReportGeneratorImpl.class)); 
                //OrderReportGeneratorImpl implements ReportGenerator
                return reportList; //created the bean which should be autowired wherever needed!
            }
        }
    

    当我在调试中运行代码时,我可以看到 config 类实际上是创建bean并将其自动连接到 报表工厂 报表工厂

    最重要的是,在所有bean初始化完成后 reportFactory 实例的 reportlist 中的实例 controller

    报告列表 有两个完全不同的条目,在 报表工厂

    有了这些,请帮帮我!

    P、 这是一个网络应用程序,我正在使用springBoot。

    1 回复  |  直到 7 年前
        1
  •  0
  •   bibliophilsagar    7 年前

    对于稍后可能访问此的人。

    ReportFactory.java

    @Component
    public class ReportFactory {
    
        @Resource // It was autowired here
        Map<String, ReportGenerator> reportList;
    
        public ReportGenerator<?> getReportGenerator(String reportType) {
    
            return reportList.get(reportType.toLowerCase());
        }
    }