SpringApplication.run主要方法

问题描述 投票:29回答:3

我使用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框架。我怎样才能做到这一点?

java eclipse spring spring-boot
3个回答
49
投票

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

Application.java

@SpringBootApplication
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
    }
}

Why not SpringApplication.run(ReconTool.class, args)

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

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


11
投票

使用:

@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方法下添加代码的另一种方法是使用一个实现CommandLineRunner的Spring Bean。那看起来像是:

@Component
public class ReconTool implements CommandLineRunner {

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

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

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


0
投票

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

@SpringBootApplication
public class ChildApplication extends ParentApplication{
    public static void main(String[] args) {
        SpringApplication.run(ChildApplication.class, args);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.