繁体   English   中英

在Springboot中通过自动装配获取NullpointerException(奇怪的情况)

[英]Getting NullpointerException with autowiring in springboot (weird scenario)

我知道这个特定的问题有很多答案,而且我知道可能由于各种情况而发生这种情况。

但是我想我错了,鉴于我的情况,我不知道所有可能的组合。 让我分享代码片段,以便代码可以说明一切。

控制器类

@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);
    }
}

我得到的是位于第43行的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另一个依赖reportList ,该bean来自于下面的类。

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并将其自动装配到ReportFactory 但是,同一个ReportFactory bean不会自动连接到控制器类。

在所有bean初始化完成之后,最reportFactory是,当我检查调试值时, reportlist实例在controllerreportlist实例中具有空值。

但是报告reportlist有两个完全不同的条目,在reportFactory类中从未提及reportFactory

有了这些,请在这里帮助我!

PS这是一个webapp,我正在使用springBoot。

对于以后可能会访问此对象的人。

如Mallikarjun所建议,以下更改对我有所帮助。

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());
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM