Сервис @Autowiring дает исключение NullPointerException - PullRequest
1 голос
/ 08 ноября 2019

Я пытаюсь автоматически связать мой класс обслуживания, но он всегда дает мне исключение нулевого указателя. Таблица для сущностей успешно создается.

Мой класс приложений

import com.pubg.players.client.Main;

@SpringBootApplication
@PropertySource("classpath:application.properties")
public class PlayersApplication {

    public static void main(String[] args) {
        SpringApplication.run(PlayersApplication.class, args);
        Main main = new Main();
        main.method();
    }

}

Мой основной класс

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import com.pubg.players.entity.Profile;
import com.pubg.players.service.ProfileService;

@Component
public class Main {

    @Autowired
    ProfileService service;

//  @Autowired
//  ApplicationContext applicationContext;

    public void method() {

        System.out.println("Enter Choice");
        System.out.println(
                "1:Create Player\n2:Get All Players\n3:Get Player With Highest Kills\n4:Modify The Best Players Highest Kills\n5:Delete Player\n6:Exit\n\n");
        System.out.println("Enter Choice:");
        Scanner sc = new Scanner(System.in);
        int choice = 0;
//      System.out.println(Arrays.asList(applicationContext.getBeanDefinitionNames()));
        do {
            choice = sc.nextInt();
            switch (choice) {
            case 1: {
                System.out.println("Enter User Name and Highest Kills");
                Profile profile = new Profile(sc.next(), sc.nextInt());
                service.createProfile(profile);
                System.out.println("Profile Created With Details :");
                break;
            }
            case 2: {
                service.getAllProfiles().forEach(i -> System.out.println(i));
                break;
            }
            case 3: {
                System.out.println(service.getProfileWithHighestKills());
                break;
            }
            case 4: {
                System.out.println("Enter User Name To Modify");
                String userName = sc.next();
                Profile profile = service.getProfileByName(userName);
                System.out.println("Enter New Kills");
                int newKills = sc.nextInt();
                profile.setHighestKills(newKills);
                service.modifyProfile(profile);
                System.out.println("Profile Modified \n Proof:-" + service.createProfile(profile));
                break;
            }
            case 5: {
                System.out.println("Enter User Name To Delete");
                String userName = sc.next();
                service.deleteProfile(userName);
                break;
            }

            default: {
                System.out.println("You Had One Job, Shame On You\n\n\n");
                System.exit(0);
                break;
            }
            }
        } while (choice != 6);
    }

}

Мой класс обслуживания

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.pubg.players.entity.Profile;
import com.pubg.players.repository.ProfileRepository;
import com.pubg.players.service.ProfileService;

@Service
public class ServiceImpl implements ProfileService {

    @Autowired
    ProfileRepository repository;

    @Override
    public Profile createProfile(Profile profile) {
        return repository.save(profile);
    }

    @Override
    public List<Profile> getAllProfiles() {
        return repository.findAll();
    }

    @Override
    public Profile getProfileByName(String name) {
        return repository.getProfileByUserName(name);
    }

    @Override
    public Profile getProfileWithHighestKills() {
        return repository.findAll(Sort.by(Sort.Direction.DESC, "highestKills")).get(0);

    }

    @Override
    public Profile modifyProfile(Profile profile) {
        return repository.saveAndFlush(profile);
    }

    @Override
    public Profile deleteProfile(String name) {
        repository.delete(repository.getProfileByUserName(name));
        return repository.getProfileByUserName(name);
    }

}

Мой сервисный интерфейс

public interface ProfileService {

    public Profile createProfile(Profile profile);

    public List<Profile> getAllProfiles();

    public Profile getProfileByName(String name);

    public Profile getProfileWithHighestKills();

    public Profile modifyProfile(Profile profile);

    public Profile deleteProfile(String name);

}

Я также пытался распечатать все компоненты в контексте приложения, но контекст приложения автоматической разводки также дает исключение нулевого указателя.

Вот ссылка на git hub для кода https://github.com/Lucifer-77/Players-Spring-Boot.git

Не знаю, как поступить. Любая помощь очень ценится

My StackTrace: -

Enter Choice
1:Create Player
2:Get All Players
3:Get Player With Highest Kills
4:Modify The Best Players Highest Kills
5:Delete Player
6:Exit


Enter Choice:
1
Enter User Name and Highest Kills
Harry
15
Exception in thread "restartedMain" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.lang.NullPointerException
    at com.pubg.players.client.Main.method(Main.java:37)
    at com.pubg.players.PlayersApplication.main(PlayersApplication.java:16)
    ... 5 more

1 Ответ

3 голосов
/ 08 ноября 2019

Проблема в том, что вы создаете экземпляр класса Main:

Main main = new Main();

Когда вы используете Spring, вы передаете контроль над созданием экземпляра в Spring Container, и вам абсолютно не следует создавать такой класс, какэто. Внедрение зависимостей будет работать только на bean-компонентах, управляемых (созданных) Spring.

Тем не менее, если вы хотите выполнить код после запуска контекста, вы должны использовать прослушиватели контекста Spring, например:

@Component
public class SampleContextListener {

    @Autowired
    private Main main;

    @EventListener(classes = { ContextStartedEvent.class })
    public void onStartup() {
        main.method();
    }
}

Если вы хотите выполнить до того, как Spring получит контроль и запустит получение контекста, вы еще не можете использовать Spring DI. В любом случае, похоже, что вам не нужно ничего из этих двух.

Теперь, если вы хотите, чтобы приложение взаимодействовало с терминалом, а также использовало Spring, вам следует взглянуть на проект Spring Shell:

https://projects.spring.io/spring-shell/

Надеюсь, это поможет.

...