> 文章列表 > Springboot 同一个模块多个启动类,指定mainclass运行

Springboot 同一个模块多个启动类,指定mainclass运行

Springboot 同一个模块多个启动类,指定mainclass运行

使用场景

同一个模块有三个springboot启动类,公用一个service,运行时想通过指定启动类的方式分别执行程序,结构如下图,其实是打了一个包

然后我们打包,哎打不了,idea告诉我们有多个启动类,莫慌

在pom中找到<build>标签 加上start-class即可

 <properties><start-class>xxx.xxx.ekr.transfer.EkrKeJiBaseDayIncreaseApplication</start-class></properties>...   <build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><includeSystemScope>true</includeSystemScope><addResources>true</addResources><mainClass>${start-class}</mainClass>
<!--                    <layout>ZIP</layout>--></configuration><executions><execution><goals><goal>repackage</goal></goals></execution></executions></plugin></plugins></build>

问题分析 

 如果执行:

java -jar ekr-transfer.jar

那么会执行服务的的所有主函数。这时候需要使用@ComponentScan排除其他的启动类,如下代码,在excludeFilters中排除了另外两个启动类。

SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@ComponentScan(basePackages = "xxx.xxx.ekr",excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {EkrKeJiBaseFullInitApplication.class,EkrXuBianFullInitApplication.class}))
public class EkrKeJiBaseDayIncreaseApplication implements ApplicationRunner {@AutowiredKBaseSyncService kBaseSyncService;public static void main(String[] args) {new SpringApplicationBuilder().sources(EkrKeJiBaseDayIncreaseApplication.class).web(WebApplicationType.NONE).run(args);}...
}

我们如何指定执行测试类中的主函数呢? 一开始是想到用:

java -cp  ekr-transfer.jar xxx.xxx.ekr.transfer.EkrKeJiBaseDayIncreaseApplication

但是提示无法找到主函数:Error: Could not find or load main class

原因是SpringBoot打包时,把所有的类都放到了BOOT-INF/classes下,而BOOT-INF不是一个合法的包名。 其实正确的方法如下:

java -cp ekr-transfer.jar -Dloader.main=xxx.xxx.ekr.transfer.EkrKeJiBaseDayIncreaseApplication org.springframework.boot.loader.PropertiesLauncher

解决方案

java -cp ekr-transfer.jar -Dloader.main=xxx.xxx.ekr.transfer.EkrKeJiBaseDayIncreaseApplication org.springframework.boot.loader.PropertiesLauncher

启动的主函数是org.springframework.boot.loader.PropertiesLauncher,让它去找到EkrKeJiBaseDayIncreaseApplication执行