Java SpringApplication.runmain方法

Java SpringApplication.runmain方法,java,eclipse,spring,spring-boot,Java,Eclipse,Spring,Spring Boot,我使用SpringStarter项目模板在Eclipse中创建了一个项目 它自动创建了一个应用程序类文件,该路径与POM.xml文件中的路径匹配,因此一切正常。下面是应用程序类: @Configuration @ComponentScan @EnableAutoConfiguration public class Application { public static void main(String[] args) { //SpringApplication.run(

我使用SpringStarter项目模板在Eclipse中创建了一个项目

它自动创建了一个应用程序类文件,该路径与POM.xml文件中的路径匹配,因此一切正常。下面是应用程序类:

@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框架。如何执行此操作?

使用:

@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引导运行

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

@Component
public class ReconTool implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
       //implement your business logic here
    }
}
从Spring的官方指南库中查看指南


可以找到完整的Spring引导文档

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

Application.java
ReconTool.java
为什么不
SpringApplication.run(ReconTool.class,args)
因为这样spring没有完全配置(没有组件扫描等)。只创建run()中定义的bean(ReconTool)


示例项目:

另一种方法是扩展应用程序(就像我的应用程序继承和自定义父级一样)。它会自动调用父级及其commandlinerunner

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

你是说你想用maven而不是IDE来启动这个应用程序?你的工具是Spring应用程序?或者是普通的Java应用程序?你窃取了我所有的想法:)就像我们在并行思考:)我想你的意思是:SpringApplication.run(ReconTool.class,args);但是你是真的,
SpringApplication.run(ReconTool.class,args)
也能工作:)我宁愿离开
SpringApplication.run(Application.class
,因为这样做,第二个解决方案对我来说太神奇了:)你的解决方案没有
@组件
:)现在,你可以替换
@配置
>,
@组件扫描
@EnableAutoConfiguration
并改用
@springbootplication
@Component
public class ReconTool implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        main(args);
    }

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