java.lang.NullPointerException: Cannot invokeController.addFlight()“,因为 Controller 为 null

java.lang.NullPointerException: Cannot invokeController.addFlight()" because Controller is null

提问人:Kavi 提问时间:9/20/2023 最后编辑:Kavi 更新时间:9/26/2023 访问量:78

问:

我面临空指针异常。你能帮我解释一下实际问题是什么以及我做错了什么吗?请原谅粗略编码,因为我是初学者。

这是错误:

线程“main”java.lang.NullPointerException 中的异常:无法调用“com.org.Controller.Controller.addFlight()”,因为“com.org.App.controller”为空 在com.org.App.main(App.java:22)

这些是类:

应用程序

package com.org;

import com.org.Config.AppConfig;
import com.org.Controller.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.Scanner;

public class App {

    @Autowired
    public static Controller controller;

        public static void main(String[] args) {
            System.out.println("Hello, Welcome to AirGO Airline");
            System.out.println("Please chose what you would like to do");
            System.out.println("1.Add Flight:");
            System.out.println("2.Search Flight");
            Scanner scanner=new Scanner(System.in);
            Integer userChoice= scanner.nextInt();
            if (1==userChoice){
                controller.addFlight();
            } else if (2==userChoice) {
                controller.showFlight();
            }
            else
            System.out.println("Please Enter a Valid Input");
        }
}

Controller //假控制器类

package com.org.Controller;

import com.org.Config.AppConfig;
import com.org.Domain.Flight;
import com.org.Service.FlightServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;


import java.time.LocalDate;
@Component
public class Controller {

    @Autowired
    FlightServiceImpl flightService= new FlightServiceImpl();
    public void addFlight(){
new AnnotationConfigApplicationContext(AppConfig.class);
        Flight flight=new Flight();
        flight.setAirlines("Indigo");
        flight.setSource("India");
        flight.setDestination("Japan");
        flight.setFare(50456.54);
        LocalDate date= LocalDate.now();
        flight.setJourneyDate(date);
        flight.setSeatCount(2);
        flightService.addFlight(flight);
    }

    public void showFlight(){
        ApplicationContext applicationContext= new AnnotationConfigApplicationContext(AppConfig.class);
        FlightServiceImpl flightService= applicationContext.getBean(FlightServiceImpl.class);
        LocalDate date= LocalDate.now();
//not complete
    }
}

服务

package com.org.Service;

import com.org.Domain.Flight;
import com.org.Repository.FlightRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class FlightServiceImpl implements FlightService{

    @Autowired
    FlightRepositoryImpl flightRepository;


    @Override
    public void addFlight(Flight flight) {
        try{
            flightRepository.addFlight(flight);
        }catch (Exception e){
            System.out.println("Flight Insertion Unsuccessful, Cannot connect to Database....");
        }

    }
}

CONFIG 类

package com.org.Config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.org")
public class AppConfig {
    //Beans AutoGenerated
}

域类

package com.org.Domain;

import java.time.LocalDate;

public class Flight {
    private String flightId;
    private String airlines;
    private String source;
    private String destination;
    private double fare;
    private LocalDate journeyDate;
    private Integer seatCount;

    public Flight() {
    }

    public String getFlightId() {
        return flightId;
    }

    public void setFlightId(String flightId) {
        this.flightId = flightId;
    }

    public String getAirlines() {
        return airlines;
    }

    public void setAirlines(String airlines) {
        this.airlines = airlines;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public String getDestination() {
        return destination;
    }

    public void setDestination(String destination) {
        this.destination = destination;
    }

    public double getFare() {
        return fare;
    }

    public void setFare(double fare) {
        this.fare = fare;
    }

    public LocalDate getJourneyDate() {
        return journeyDate;
    }

    public void setJourneyDate(LocalDate journeyDate) {
        this.journeyDate = journeyDate;
    }

    public Integer getSeatCount() {
        return seatCount;
    }

    public void setSeatCount(Integer seatCount) {
        this.seatCount = seatCount;
    }

    @Override
    public String toString() {
        return "Flight{" +
                "flightId='" + flightId + '\'' +
                ", airlines='" + airlines + '\'' +
                ", source='" + source + '\'' +
                ", destination='" + destination + '\'' +
                ", fare=" + fare +
                ", journeyDate=" + journeyDate +
                ", seatCount=" + seatCount +
                '}';
    }
}

存储库

package com.org.Repository;

import com.org.Domain.Flight;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.Map;

@Repository
public class FlightRepositoryImpl implements FlightRepository{

    private static Integer flightId = 1000;
    @Override
    public void addFlight(Flight flight) {
        Map<Integer, Flight> database= new HashMap<Integer, Flight>();
        flightId+=1;
        database.put(flightId,flight);
        System.out.println("Added flight details are: "+ flight.toString());
    }
}
Java Spring NullPointerException 逻辑

评论

0赞 Kavi 9/20/2023
谢谢它有效,但您能否解释一下这如何影响,例如当我不使用新运算符创建实例时。
0赞 f1sh 9/20/2023
这回答了你的问题吗?SpringApplication.run main 方法

答:

1赞 Kunal Varpe 9/20/2023 #1

更新您的配置类,如下所示。

package com.org.Config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.org")
public class AppConfig {
    //Beans AutoGenerated

    @Bean
    public Controller controller() {
       return new Controller();
    }
}

但在理想的世界场景中。控制器类应使用 或 进行注释,并映射到正确的 http 终结点映射。@RestController@Controller

希望这会有所帮助。

更新: 如果您使用的是 Spring-Boot 或使用 Spring,则您的 App 类也会丢失。根据用例更新您的类。@SpringBootApplication@Component

Spring Boot:

@SpringBootApplication
public class App {

    @Autowired
    public static Controller controller;

        public static void main(String[] args) { 
           SpringApplication.run(args, App.class);
        }
}

春天:

@Component
public class App {

    public static Controller controller;

        public static void main(String[] args) {
            ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
            controller = context.getBean(Controller.class);
            System.out.println("Hello, Welcome to AirGO Airline");
            System.out.println("Please chose what you would like to do");
            System.out.println("1.Add Flight:");
            System.out.println("2.Search Flight");
            Scanner scanner=new Scanner(System.in);
            Integer userChoice= scanner.nextInt();
            if (1==userChoice){
                controller.addFlight();
            } else if (2==userChoice) {
                controller.showFlight();
            }
            else
            System.out.println("Please Enter a Valid Input");
        }
}

我想我更喜欢Spring Boot的方式。如果你在命令行应用程序上需要进一步的帮助,请在 GitHub 上创建一个带有示例代码的存储库并在这里分享,我们可以讨论和贡献。

评论

0赞 Kavi 9/20/2023
我更新了相同的内容,并尝试使用“@Component”,因为我使用的是“@ComponentScan”,但问题仍然存在。编辑:在 App 类中创建 Controller 类的新实例后,它正在工作。谢谢
1赞 f1sh 9/20/2023
这里的实际问题是,这个应用程序是使用不涉及springboot的常规启动的,因此没有主动的依赖注入机制。因此,不会发生自动接线。main