如何通过@Profile实现多@SpringBootApplication配置并适配mvn运行?
解决Spring Boot多Profile启动类的mvn运行冲突问题
当你需要用不同Profile加载不同包下的代码,但遇到多main()方法导致mvn运行报错的情况,可以试试这几种方案:
方案一:写一个统一的主入口类
不用保留多个带main()的启动类,而是写一个全局主类,根据激活的Profile动态加载对应的配置类。
示例代码:
package com.myapp; import org.springframework.boot.SpringApplication; import com.myapp.config1.MyApp1; import com.myapp.config2.MyApp2; public class UnifiedMain { public static void main(String[] args) { String[] activeProfiles = SpringApplication.run().getEnvironment().getActiveProfiles(); if (activeProfiles.length == 0) { throw new IllegalArgumentException("请指定激活的Profile"); } switch (activeProfiles[0]) { case "app1": SpringApplication.run(MyApp1.class, args); break; case "app2": SpringApplication.run(MyApp2.class, args); break; default: throw new IllegalArgumentException("不支持的Profile: " + activeProfiles[0]); } } }
注意:原MyApp1和MyApp2类保留@SpringBootApplication和@Profile注解,但可以去掉自身的main()方法,仅作为配置类使用。
方案二:运行mvn命令时直接指定主类
无需修改代码,每次运行通过参数指定要启动的主类,命令格式如下:
# 启动app1对应的主类 mvn spring-boot:run -Dspring.profiles.active=app1 -Dspring-boot.run.main-class=com.myapp.config1.MyApp1 # 启动app2对应的主类 mvn spring-boot:run -Dspring.profiles.active=app2 -Dspring-boot.run.main-class=com.myapp.config2.MyApp2
这种方式灵活,适合临时测试不同Profile的场景。
方案三:在pom.xml中配置Maven Profile
把Spring Boot的Profile和Maven的Profile绑定,每个Maven Profile对应一个主类,运行时切换Maven Profile即可。
pom.xml配置示例:
<profiles> <profile> <id>app1</id> <properties> <spring.boot.main.class>com.myapp.config1.MyApp1</spring.boot.main.class> </properties> </profile> <profile> <id>app2</id> <properties> <spring.boot.main.class>com.myapp.config2.MyApp2</spring.boot.main.class> </properties> </profile> </profiles> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <mainClass>${spring.boot.main.class}</mainClass> </configuration> </plugin> </plugins> </build>
运行时只需指定Maven Profile:
mvn spring-boot:run -P app1 # 或者 mvn spring-boot:run -P app2
内容的提问来源于stack exchange,提问作者membersound
相关产品推荐
相关产品推荐

