简体   繁体   中英

Springboot - Save entity in 'normal' class

I'm pretty new to Springboot and Java in general and because we got this in school I'm fiddeling arround.

I'm now trying to save an entity outside of the Springboot Entities, Repositories or RestController with the following code:

InfMApplication.java:

package com.domain.springboot;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.domain.springboot.repositories.MovieRepository;
import com.domain.springboot.services.MovieImport;

@SpringBootApplication
public class InfMApplication {
    
    public static void main(String[] args) {
        SpringApplication.run(InfMApplication.class, args);
        MovieImport movieImport = new MovieImport();
        movieImport.saveToDb();
    }
    
}

MovieImport.java:

package com.domain.springboot.services;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.io.*;
import java.net.URL;

import com.google.gson.Gson;

import com.domain.omdbapi.entities.Movie;
import com.domain.omdbapi.entities.SearchResponse;
import com.domain.omdbapi.entities.SearchResult;
import com.domain.springboot.repositories.ComplexRepository;
import com.domain.springboot.repositories.DocumentRepository;
import com.domain.springboot.repositories.MovieRepository;
import com.domain.springboot.repositories.SimpleRepository;

@Service
public class MovieImport {
    
    private final MovieRepository movieRepository;
    
    public MovieImport(MovieRepository movieRepository){
          this.movieRepository =  movieRepository;
        }
    
    public void main() {
        String randomImdbId = fetchRandomMovie();
        Movie movie = fetchMovieDetails(randomImdbId);
        saveToDb(movie);
    }
    
    public void saveToDb(Movie movie) {
        com.domain.springboot.entities.Movie springbootMovie = new com.domain.springboot.entities.Movie(movie.Title, movie.imdbID);
        this.movieRepository.save(springbootMovie);
        
        
    }
    
    public String fetchRandomMovie() {
        String randomWord = getRandomWord();
        String url = "https://www.omdbapi.com/?apikey=<API_KEY>&type=movie&s=" + randomWord;
        HttpClient client = HttpClient.newHttpClient();
        
        HttpRequest request = HttpRequest.newBuilder(
                URI.create(url))
            .header("accept", "application/json")
            .build();
        
        HttpResponse<String> response = null;

        try {
            response = client.send(request, BodyHandlers.ofString());
        } catch (Exception e) {
            System.out.println(e);
        }
        
        Gson gson = new Gson();
        SearchResponse searchResponse = gson.fromJson(response.body(), SearchResponse.class);
        
        int randomIndex = new Random().nextInt(0, searchResponse.getSearch().length);
        SearchResult randomResult = searchResponse.getSearch()[randomIndex];
        
        return randomResult.getImdbID();
    }
    
    
    public Movie fetchMovieDetails(String imdbId) {
        String url = "https://www.omdbapi.com/?apikey=<API_KEY>&type=movie&plot=full&i=" + imdbId;
        HttpClient client = HttpClient.newHttpClient();
        
        HttpRequest request = HttpRequest.newBuilder(
                URI.create(url))
            .header("accept", "application/json")
            .build();
        
        HttpResponse<String> response = null;

        try {
            response = client.send(request, BodyHandlers.ofString());
        } catch (Exception e) {
            System.out.println(e);
        }
        
        Gson gson = new Gson();
        Movie movie = gson.fromJson(response.body(), Movie.class);
        
        return movie;
    }
    
    public String getRandomWord() {
        URL resource = getClass().getClassLoader().getResource("Wordlist.txt");
        
        List<String> words = new ArrayList<>();
        
        try {
            File file = new File(resource.toURI());
            words =  Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        int randomIndex = new Random().nextInt(0, words.size());
        
        return words.get(randomIndex);
    }

}

If I use "this.movieRepository.save(movieObject);" to save a movie in the MovieRestController the same way, it works. I also tried adding the "@Autowire" annotation, but this didn't work.

I always get the error

java.lang.NullPointerException: Cannot invoke "com.domain.springboot.repositories.MovieRepository.save(Object)" because "this.movieRepository" is null

How can I get to use the movieRepository in other Java classes like in the RestControllers?

java.lang.NullPointerException: Cannot invoke "com.domain.springboot.repositories.MovieRepository.save(Object)" because "this.movieRepository" is null

Above is perfectly valid if we look at your following shared code.

public class MovieImport {
    
    private MovieRepository movieRepository;
    
    public void saveToDb() {
        // Create movie
        com.domain.springboot.entities.Movie springbootMovie = new com.domain.springboot.entities.Movie("Iron Man", "284cb8fgf");
        this.movieRepository.save(springbootMovie);
    }
}

You've to correct certain things in your code base. First you're not initializing the movieRepository and therefore, you're getting the null pointer exception. As you've been using the springboot you can use construction injection to initialized the field by spring container. Also. this class should be scanned by spring and you should also put some annotation such as Component or Service on top of it.

Following will work if your MovieImport and MovieRepository classess will scan by springboot.

package com.domain;
import com.domain.omdbapi.entities.Movie;
import com.domain.springboot.repositories.MovieRepository;

@Service
public class MovieImport {
    
    private final MovieRepository movieRepository;

    public MovieImport(MovieRepository movieRepository){
      this.movieRepository =  movieRepository;
    }
    
    public void saveToDb() {
        // Create movie
        com.domain.springboot.entities.Movie springbootMovie = new com.domain.springboot.entities.Movie("Iron Man", "284cb8fgf");
        this.movieRepository.save(springbootMovie);
    }
}

Updated

@SpringBootApplication  
public class InfMApplication implements CommandLineRunner {

    @Autowired
    private MovieImport movieImport;

    public static void main(String[] args) {
        SpringApplication.run(InfMApplication.class, args);
    }
    
    @Override
    public void run(String... args) throws Exception {
      movieImport.saveToDb();
    }

}

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