在我的 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,这段代码中有什么错误?
1条答案
按热度按时间mec1mxoz1#
您正在启动main方法而不启动Spring,因此Spring不会创建RecordingService。可以使用CommandLineRunner对其进行更改: