简体   繁体   English

如何在自动连线的JdbcTemplate上修复NullPointerException

[英]How to fix NullPointerException on Autowired JdbcTemplate

I am re-writing my question to hopefully make more sense and get some help. 我正在重新编写我的问题,希望有更多的道理并获得帮助。

I have a Controller , 2 ClassRepository , and 2 Service classes (one of which is not annotated with @Service as I get an error when I annotate it, so instead I just use it as a class) 我有一个Controller ,2 ClassRepository和2 Service类(其中一个未使用@Service进行注释,因为在注释时会出现错误,因此我只是将其用作类)

The class not annotated with @Service I simply pass the rateRepository object from the annotated Service to the unannotated service. 没有用@Service注释的类,我只是将rateRepository对象从带注释的服务传递给了无注释的服务。

If I execute the following code in my annotated service 如果我在带注释的服务中执行以下代码

String zone = rateRepository.getPurolatorZone(request.getShipToZip().substring(0,3));

it works great. 它很棒。

however in my unannotated class where i instantiate the class 但是在我未注释的课程中,我实例化了该课程

InternationalRateService internationalRateService = new InternationalRateService(this.rateRepository);

UPDATE: I annotated my InternationalRateService class with @Service and decided to autowire the repository itself, and I still get a null pointer exception on the getPurolatorZone method.. I dont understand why it works in one service but not the other when they are set up the same. 更新:我用@Service注释了InternationalRateService类,并决定自动连接存储库本身,并且在getPurolatorZone方法上仍然收到空指针异常。.我不明白为什么在设置一个服务时它不能在另一个服务中工作相同。

Second Update: as it turns out, im an idiot because i didn't even think to check that it was possible that the string i pass to the repository was what was actually throwing the error. 第二次更新:事实证明,我是个白痴,因为我什至没有想到要检查传递给存储库的字符串是否确实是引发错误的原因。 Turns out I never set the local shiptozip variable so. 原来我从来没有设置本地shiptozip变量。 yea im an idiot . 是的是个白痴。

Spring will inject dependencies only in spring managed beans. Spring将仅在Spring托管bean中注入依赖项。 If you create an object with new then it's not spring managed bean. 如果使用new创建对象,那么它不是spring托管的bean。

In your case, object of InternationalRateService is not managed, as you created by new operator. 在您的情况下,不像由new操作员创建的那样管理InternationalRateService对象。

So, inject InternationalRateService in your controller, so that all dependencies are injected 因此,在您的控制器中注入InternationalRateService ,以便注入所有依赖项

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

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