@Autowiring服务提供NullPointerException

我正在尝试自动连接我的服务类,但是它总是给我Null Pointer Exception。实体表正在成功创建。

我的AppLication类

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);

}

我也曾尝试在应用程序上下文中打印所有bean,但是自动装配应用程序上下文也会使Null指针异常。

这里是git hub链接到代码 https://github.com/Lucifer-77/Players-Spring-Boot.git

不知道如何进行。非常感谢的任何帮助

我的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
lantianniu 回答:@Autowiring服务提供NullPointerException

问题在于您正在实例化Main类:

Main main = new Main();

使用Spring时,应将对实例化的控制权传递给Spring Container,并且绝对不应构造这样的类。依赖项注入仅适用于由Spring管理(构造)的bean。

也就是说,如果要在上下文启动后执行代码,则应使用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/

希望有帮助。

本文链接:https://www.f2er.com/3139859.html

大家都在问