我正在构建一个将从命令行调用的Spring Boot应用程序。我将一些参数传递给应用程序,但是在从此类中调用服务时遇到问题:
@SpringBootApplication public class App{ public static void main(String[] args) { SpringApplication.run(App.class, args); App app = new App(); app.myMethod(); } @Autowired private MyService myService; private void myMethod(){ myService.save(); } }
我正在尝试从主体内部调用方法,但出现错误:
Exception in thread "main" java.lang.NullPointerException at com.ef.Parser.App.myMethod(Application.java:26) at com.ef.Parser.App.main(Application.java:18)
您可以创建一个实现CommandLineRunner的类,并在应用启动后调用该类
@Component public class CommandLineAppStartupRunner implements CommandLineRunner { @Autowired private MyService myService; @Override public void run(String...args) throws Exception { myService.save(); } }
您可以在此处获得更多信息