【问题标题】:how to switch spring boot startup class based on active spring profile如何根据活动的弹簧配置文件切换弹簧启动启动类
【发布时间】:2016-12-09 18:59:00
【问题描述】:

我想我误解了 Spring 引导配置文件的功能。 我的 Spring Boot 应用程序中有两个单独的启动类(ApplicationLocal 和 ApplicationProduction), 这些类是这样注释的

@SpringBootApplication
@EnableSwagger2
@Import(value={Config.class})
@ComponentScan(basePackages={"com.abc.*"})
@Profile("local")
public class ApplicationLocal extends SpringBootServletInitializer {
//

@SpringBootApplication
@EnableSwagger2
@Import(value={Config.class})
@ComponentScan(basePackages={"com.abc.*"})
@Profile("production")
public class ApplicationProduction extends SpringBootServletInitializer {
//

并且我希望 Spring 引导在运行时根据 -Dspring.profiles.active jvm 争论的值获取适当的启动类。 但它对我不起作用,除非我在 pom.xml 部分中提到 start-class 像这样。。

<properties>
    <start-class>com.abc.web.service.ApplicationLocal</start-class>
</properties>

如果我没有在 pom.xml 中提及 start-class,则会收到以下错误: (我按以下方式运行应用程序

mvn spring-boot:run  -Drun.jvmArguments=" -Dspring.profiles.active=local"

我收到以下错误

[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.3.3.RELEASE:run (default-cli) on project payee-list-ws: Execution default-cli of goal org.springframework.boot:spring-boot-maven-plugin:1.3.3.RELEASE:run failed: Unable to find a single main class from the following candidates [com.abc.web.service.ApplicationProduction, com.abc.web.service.ApplicationLocal] -> [Help 1]

【问题讨论】:

  • 真的需要不同的类吗?每个配置文件有这么多不同的业务逻辑吗?还是只有一些配置不同,比如不同的数据库连接等?

标签: spring spring-boot


【解决方案1】:

您可以为每个环境创建一个主类和两个配置:

@SpringBootApplication
@EnableSwagger2
@Import(value={Config.class})
@ComponentScan(basePackages={"com.abc.*"})
public class Application extends SpringBootServletInitializer {
//

@Configuration
@Profile("production")
public class ConfigProduction {
    //...
}

@Configuration
@Profile("Local")
public class ConfigLocal {
    //...
}

由于主类将扫描 bean,Spring 将根据您的实际配置文件选择正确的配置。

【讨论】:

    猜你喜欢
    • 2018-09-08
    • 2022-01-04
    • 1970-01-01
    • 2016-12-25
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    • 2018-04-27
    • 2018-11-18
    相关资源
    最近更新 更多