SpringApplication.run主要方法

Ale*_*lls 32 java eclipse spring spring-boot

我使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

但是,我宁愿不必注释掉那一行,并使用完整的Spring框架.我怎样才能做到这一点?

Mar*_*szS 57

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

Application.java

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

  • 现在,您可以替换`@Configuration`、`@ComponentScan` 和`@EnableAutoConfiguration` 并使用`@SpringBootApplication` 代替 (2认同)

geo*_*and 11

使用:

@ComponentScan
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);  

        //do your ReconTool stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

将在所有情况下工作.是否要从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
    }
}
Run Code Online (Sandbox Code Playgroud)

查看Spring官方指南库中的指南.

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

  • 它像我们并行思考的接缝:) (2认同)