I was testing out some stuff and came across this weird behavior.
What I want to do
Let's say I want to pre-load some values into a repository using a local file, request, or whatever.
Normally I'd put these in a constructor like this:
@Service
public class PointOfInterestService {
@Autowired
private PointOfInterestRepository pointOfInterestRepository;
public PointOfInterestService() {
try {
String jsonStr = Helper.isToString(new FileInputStream(new File("test.json")));
JSONObject json = new JSONObject(jsonStr);
JSONArray entries = json.getJSONArray("features");
for (Object element : entries) {
try {
//new PointOfInterest(...)
//read file and do stuff
//...
//finally, let's save the object
this.registerPointOfInterest(pointOfInterest);
}
} catch (Exception e) {
if (!(e instanceof JSONException)) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void registerPointOfInterest(PointOfInterest pointOfInterest) {
pointOfInterestRepository.save(pointOfInterest);
}
}
When the constructor runs, a NullPointerException
pops up whenever registerPointOfInterest
is thrown.
Using the debugger I realized that for some reason the repository is null (and thus the exception is thrown.
This is the repository class, which is pretty simple:
package com.example.demo.PointOfInterest;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PointOfInterestRepository extends JpaRepository<PointOfInterest, String> {
}
Is there any easy work-around to read said file in the constructor? Thanks!
>);`.
– chrylis -cautiouslyoptimistic- Apr 26 '20 at 03:13