SpringApplication.run主要方法

我使用Spring Starter项目模板在Eclipse中创建了一个项目。

它自动创建了一个Application类文件,该路径与POM.xml文件中的路径匹配,所以一切都很好。 这是Application类:

@Configuration @ComponentScan @EnableAutoConfiguration public class Application { public static void main(String[] args) { //SpringApplication.run(ReconTool.class, args); ReconTool.main(args); } } 

这是我正在构建的命令行应用程序,为了让它运行我必须注释掉SpringApplication.run行,只需从我的其他类中添加main方法即可运行。 除了这个快速的jerry-rig之外,我可以使用Maven构建它,它可以作为Spring应用程序运行。

但是,我宁愿不必评论该行,并使用完整的Spring框架。 我怎样才能做到这一点?

您需要运行Application.run()因为此方法启动整个Spring Framework。 下面的代码将main()与Spring Boot集成在一起。

Application.java

 @Configuration @ComponentScan @EnableAutoConfiguration public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } 

ReconTool.java

 @Component public class ReconTool implements CommandLineRunner { @Override public void run(String... args) throws Exception { main(args); } public static void main(String[] args) { // Recon Logic } } 

为什么不SpringApplication.run(ReconTool.class, args)

因为这种方式弹簧没有完全配置(没有组件扫描等)。 仅创建run()中定义的bean(ReconTool)。

示例项目: https : //github.com/mariuszs/spring-run-magic

使用:

 @ComponentScan @EnableAutoConfiguration public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); //do your ReconTool stuff } } 

将在所有情况下工作。 是否要从IDE或构建工具启动应用程序。

使用maven只需使用mvn spring-boot:run

在gradle中,它将是gradle bootRun

在run方法下添加代码的另一种方法是使用Spring Bean来实现CommandLineRunner 。 那看起来像是:

 @Component public class ReconTool implements CommandLineRunner { @Override public void run(String... args) throws Exception { //implement your business logic here } } 

查看Spring官方指南库中的本指南。

完整的Spring Boot文档可以在这里找到

另一种方法是扩展应用程序(因为我的应用程序是inheritance和自定义父代)。 它会自动调用父级及其命令行管理器。

 @SpringBootApplication public class ChildApplication extends ParentApplication{ public static void main(String[] args) { SpringApplication.run(ChildApplication.class, args); } }