0

Im creating a Discord Bot using SpringBoot Project (with H2 DB) and i have a little problem on it.

Im trying to save an specific object (memberTributeRepository.save(member)) using my repository class, but im getting a nullPointerException when put the autowired annotation.

Some one can help me?

Below are some excerpts from code:

REPOSITORY CLASS

@Repository
public interface MemberTributeRepository extends CrudRepository<MemberTribute, Long> {

}

Below, the class that im getting nullPointerException with Autowired annotation:

@Service
public class MemberTributeService {

    @Autowired
    MemberTributeRepository memberTributeRepository;

    public String loadTributesFromApi() {
        return ConectaApiAlbion.loadTributes();
    }

    public JSONArray processJsonFromApi() {
        JSONArray jsonArray = new JSONArray(loadTributesFromApi());
        return jsonArray;
    }

    public List<MemberTribute> buildListOfTributes() {

        List<MemberTribute> listOfMemberTribute = new ArrayList<>();

        for (int i = 0; i < processJsonFromApi().length(); i++) {

            MemberTribute member = new MemberTribute();
            member.setId(processJsonFromApi().getJSONObject(i).getString("Id"));
            member.setGuildName(processJsonFromApi().getJSONObject(i).getString("GuildName"));
            member.setName(processJsonFromApi().getJSONObject(i).getString("Name"));
            Gathering gathering = buidingGathering(i);
            member.setLifetimeStatistics(new LifetimeStatistics(gathering, LocalDateTime.now()));
            listOfMemberTribute.add(member);
            System.out.println("Salvando o membro: " + member.getName());
            //NullPointer happens below, when i try to save my object 'member'
            memberTributeRepository.save(member);

        }

        return listOfMemberTribute;
    }

    public Gathering buidingGathering(int i) {
        Gathering gathering = new Gathering();
        JSONObject PATH_TO_GATHERING = processJsonFromApi()
                .getJSONObject(i)
                .getJSONObject("LifetimeStatistics")
                .getJSONObject("Gathering");

        gathering.setTotalFibe(PATH_TO_GATHERING.getJSONObject("Fiber").getLong("Total"));
        gathering.setTotalHide(PATH_TO_GATHERING.getJSONObject("Hide").getLong("Total"));
        gathering.setTotalOre(PATH_TO_GATHERING.getJSONObject("Ore").getLong("Total"));
        gathering.setTotalRock(PATH_TO_GATHERING.getJSONObject("Rock").getLong("Total"));
        gathering.setTotalWood(PATH_TO_GATHERING.getJSONObject("Wood").getLong("Total"));
        return gathering;
    }
}

Now, the last one is the class that i use to call MemberTributeService

@Component
public class Start extends ListenerAdapter {

    private static String AUTHOR = "";

    public static void jdaBuilder () throws LoginException {
        JDA jda = JDABuilder.createDefault("xxxxxxxxxxxxxxxTOKENxxxxxxxxxxxxxxxxxx").build();
        jda.addEventListener(new Start());
    }

    @Override
    public void onMessageReceived(MessageReceivedEvent event) {
        MemberTributeService service = new MemberTributeService();

        AUTHOR = event.getAuthor().getName();
        if (event.getAuthor().isBot()) return;
        if (event.getMessage().getContentRaw().startsWith("/bot")) {
            if (event.getMessage().getContentRaw().toLowerCase().contains("tributos")) {

                event.getChannel().sendMessage("Eai " + AUTHOR + ", só de boas? ").queue();

                List<MemberTribute> listMemberTribute = service.buildListOfTributes();

                for (int i = 0; i < listMemberTribute.size(); i++) {
                    event.getChannel().sendMessage("-------------------\n" + "Nome: " + listMemberTribute.get(i).getName() +
                            "\nTotal Fiber: " + listMemberTribute.get(i).getLifetimeStatistics().getGathering().getTotalFibe() +
                            "\nTotal Ore: " + listMemberTribute.get(i).getLifetimeStatistics().getGathering().getTotalOre() +
                            "\n Total Wood: " + listMemberTribute.get(i).getLifetimeStatistics().getGathering().getTotalWood() +
                            "\n Total Rock: " + listMemberTribute.get(i).getLifetimeStatistics().getGathering().getTotalRock() +
                            "\n Total Hide: " + listMemberTribute.get(i).getLifetimeStatistics().getGathering().getTotalHide())
                            .queue();
                }

            } else {
                event.getChannel().sendMessage("Opa..  " + AUTHOR + ", não reconheci seu comando." +
                        "\n tenta utilizar /bot antes! ").queue();
            }
        }

    }

}
  • It seems your components are not getting scanned during application initialization. – rns Sep 14 '20 at 19:27
  • Do you have any sugestion how to fix it? – Pedro Sanchez Sep 14 '20 at 19:34
  • What I doubt is MemberTributeRepository is not getting initialized and hence you are getting NP exception. Is is in the same package hierarchy from where main class is present? – rns Sep 14 '20 at 19:36
  • They are in different packages.. `**Main** (package br.com.discordBot.tributes;)` `**Repository** (package br.com.discordBot.tributes.repository;)` `**MemberTributeService** (package br.com.discordBot.tributes.service;)` – Pedro Sanchez Sep 14 '20 at 19:47
  • Where is main class containing `@SpringBootApplication`? – rns Sep 14 '20 at 19:50
  • Yes.. `@SpringBootApplication public class TributesApplication {...` – Pedro Sanchez Sep 14 '20 at 19:51
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/221478/discussion-between-pedro-sanchez-and-rns). – Pedro Sanchez Sep 14 '20 at 19:59
  • This is a duplicate of a canonical question: https://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null . Don't create a MemberTributeService with new; autowire it instead. – neofelis Sep 14 '20 at 22:46
  • @neofelis, i've made this change, but i skill getting NullPointer – Pedro Sanchez Sep 14 '20 at 23:22
  • Hm! I was so convinced. Sorry, no idea what it is in that case. – neofelis Sep 15 '20 at 05:10
  • Check that in the main class, you have the @ComponentScan annotation including all packages (in this case the MemberTributeRepository) as indicated here: https://stackoverflow.com/questions/30425016/spring-boot-find-autowired-on-another-package – JLazar0 Sep 15 '20 at 17:10

0 Answers0