spring-data-jpa 如何调用主类中的仓库服务并使用主参数?

m1m5dgzv  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(174)

在我的 Boot 应用程序中,我使用main参数传递变量,并且需要调用一个方法,根据main类中的一些代码将对象保存到数据库中。
我使用的主类是这样的:

@SpringBootApplication
public class MainClass {

    @Autowired
    private RecordingService recordingService;

    public MainClass(String arg1, String arg2) {
        this.setArg1(arg1);
        this.setArg2(arg2);
    }

    public static void main(String args[]) {

        String ip = null;
        String op = null;

        if (args != null & args.length > 0) {
            for (int i = 0; i < args.length; i++) {
                if (args[i].equalsIgnoreCase("-ip")) {
                    ip = args[i + 1].trim();
                } else if (args[i].equalsIgnoreCase("-op")) {
                    op = args[i + 1].trim();
                }
                i++;
            }
        }

        if (ip == null || op == null) {
            System.out.println("Invalid input or output path.");
        } else {
            MainClass reader = new MainClass(ip, op);
            Recording recording = new Recording();
            .
            .
            some code...
            .
            .
            this.recordingService.insertIntoDB(recording);
            }
        }
    }
}

这是服务类:

@Service
public class RecordingService {

    @Autowired
    private RecordingRepository recordingRepository;

    public RecordingService() {
    }

    public void insertToDatabase(Recording recording) {
        try {
            Recording recording = new Recording();
            this.recordingRepository.save(recording);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

当我运行这段代码时,我得到了 NullPointerException,这段代码中有什么错误?

mec1mxoz

mec1mxoz1#

您正在启动main方法而不启动Spring,因此Spring不会创建RecordingService。可以使用CommandLineRunner对其进行更改:

@SpringBootApplication
public class MainClass implements CommandLineRunner {

    @Autowired
    private RecordingService recordingService;

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

    @Override
    public void run(String... args) {
        //your main code here
    }
}

相关问题