简体   繁体   中英

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)

The class not annotated with @Service I simply pass the rateRepository object from the annotated Service to the unannotated service.

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.

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. yea im an idiot .

Spring will inject dependencies only in spring managed beans. If you create an object with new then it's not spring managed bean.

In your case, object of InternationalRateService is not managed, as you created by new operator.

So, inject InternationalRateService in your controller, so that all dependencies are injected

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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