mardi 7 février 2017

java - Autowiring Repository in class that is instantiated in Spring Boot

Vote count: 0

So I have an API client type class right now, which I am trying to connect to my repository so that I can store data in the MySQL database.

The problem I'm having is that the API client class instantiates a new object of itself, so the Autowiring doesn't work correctly. I've looked around for a workaround for this problem, and I've seen a couple options, but I'm confused on how to apply them to my problem.

For reference, here are parts of some of the relevant files:

GeniusApiClient.java:

@Component
public final class GeniusApiClient {
    private final OkHttpClient client = new OkHttpClient();

    @Autowired
    private ArtistDao artistDao;

    public static void main(String[] args) throws Exception {
        GeniusApiClient geniusApiClient = new GeniusApiClient();
        String artistId = (geniusApiClient.getArtistId("Ugly Duckling"));
        ArrayList<String> artistSongIds =      geniusApiClient.getArtistSongIds(artistId);

public String getAllSongAnnotations(ArrayList<String> songIds, String artistId) {
    try {
        String annotations = artistDao.findByGeniusId(artistId).getAnnotations();
        return annotations;
    }
    catch(Exception e) {
        GeniusApiClient geniusClient = new GeniusApiClient();

        ArrayList<String> annotationList = new ArrayList<String>();

        for (String songId : songIds) {
            annotationList.add(geniusClient.getReferentAnnotations(geniusClient.getSongReferents(songId)));
        }

        String annotationString = squashAnnotationArray(annotationList);

        Artist artist = new Artist("test name for now", annotationString, artistId);
        System.out.println(artistDao);
        artistDao.save(artist);
        return annotationString;
    }
}

        System.out.println(geniusApiClient.getAllSongAnnotations(artistSongIds, artistId));
}

ArtistDao.java:

@Transactional
public interface ArtistDao extends CrudRepository<Artist, Long> {
    public Artist findByGeniusId(String geniusId);
}

The problem is that in GeniusApiClient.java in the getAllSongAnnotations method, I have a null pointer exception when I try and access the artistDao. I understand that my instantiation of this class is what is messing up the Autowiring, but I'm curious on what the best way to go about fixing this might be.

I considered making all of my methods in the class static so that I wouldn't have to instantiate a new method, but I don't think this would work very well. Any suggestions?

Thanks

asked 41 secs ago

Let's block ads! (Why?)



java - Autowiring Repository in class that is instantiated in Spring Boot

Aucun commentaire:

Enregistrer un commentaire