我使用Spring Starter项目模板在Eclipse中创建了一个项目。
它自动创建了一个应用程序类文件,并且该路径与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方法来运行。除了这个快速的曾傑瑞-rig,我可以使用Maven构建它,它在某种程度上作为Spring应用程序运行。
但是,我不希望注释掉这一行,而是使用完整的Spring框架。我该怎么做呢?
发布于 2014-06-18 03:34:59
您需要运行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
}
}为什么不使用SpringApplication.run(ReconTool.class, args)?
因为这种方式spring没有完全配置(没有组件扫描等)。只创建在run()中定义的bean (ReconTool)。
发布于 2014-06-18 03:26:27
使用:
@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中找到
发布于 2017-06-10 04:40:21
另一种方法是扩展应用程序(就像我的应用程序继承和自定义父应用程序一样)。它会自动调用父进程及其命令行运行器。
@SpringBootApplication
public class ChildApplication extends ParentApplication{
public static void main(String[] args) {
SpringApplication.run(ChildApplication.class, args);
}
}https://stackoverflow.com/questions/24271705
复制相似问题