Spring-boot my service which is autowired is null

Viewed 806

Field in my project is null and I don't have idea why. I don't initalize in project any autowired variable like new BingoGameService(); - so I don't know why I got null.

public class MessageReaction extends ListenerAdapter {
@Autowired
BingoGameService bingoGameService; //NULL

@Override
public void onMessageReceived(@Nonnull MessageReceivedEvent event) {

    if(event.getMessage().getContentRaw().equals("!createBingo")) bingoGameService.createBingoGameForUser(event.getAuthor().getIdLong());

This is my service class:

@Service
public class BingoGameService {
@Autowired
DiscordUserRepo discordUserRepo;
@Autowired
BingoBoardRepo bingoBoardRepo;
@Autowired
GameMechanics gameMechanics;

    public void createBingoGameForUser(Long id) {

if(bingoBoardRepo.findById(1L).isPresent()){
        String[][] officialBingoBoard = bingoBoardRepo.findById(1L).get().getBingoBoard();
        int[][] scoreBoard = gameMechanics.createScoreBoard(3,3);
        DiscordUser discordUserToSave = new DiscordUser();
        BingoGame bingoGame = new BingoGame(discordUserToSave, officialBingoBoard, scoreBoard);
        discordUserToSave.setUserId(id);
        discordUserToSave.setBingoGame(bingoGame);
        discordUserRepo.save(discordUserToSave);
    } 
}
2 Answers

you don't need use @Autowired if you create class with constructor. Add @Component over MessageReaction class

Spring Boot search for annotation like "@Component" "@Service" etc. if you don't include them over class name, it won't know where inject values/classes

@Component
public class MessageReaction extends ListenerAdapter {

private FooService fooService;

 public MessageReaction(FooService fooService){
  this.fooService = fooService
 }


}

Depends on the category of layering of your app, you can annotate classes as @Component, @Service or @Repository.

I didn't see any annotation for the class MessageReaction. If it is a generic component you have to annotate it with @Component.

This annotation helps Spring container to instantiate the instance of your class MessageReaction and autowire the injected dependencies. Since there is no default constructor for the class MessageReaction, you have to annotate the dependency BingoGameService with @Autowired annotation.

Related