java - 如何使用 Spring Boot 和 Maven 设置配置文件?

标签 java spring maven spring-boot

我有 2 个环境来设置我的 API,所以我有生产环境和开发环境。我首先需要找到一种自动执行此操作的方法,例如,在运行时无需发送任何参数(-D),应用程序找到一种方法来识别环境是谁,但我没有找到任何方法可以执行此操作这边走。

所以我读了一个教程,同样有一种方法来放置环境变量,并定义我的application.properties。因此,按照以下步骤:

  1. 我在应用程序中定义了 3 个文件:application.properties、application-dev.properties 和 application-prod.properties。

  2. 在 application.properties 中,我有配置 spring.profiles.active=${MYENV:local}。

  3. 在 application-dev.properties 中我有 spring.profiles.active=dev。

  4. 在 application-prod.properties 中我有 spring.profiles.active=prod。

  5. 我知道如果我传递命令 mvn spring-boot:run -Dspring-boot.run.profiles=(PROFILE) Spring 会完美选择配置文件。

我有两个问题:

  1. 我的环境变量在 Windows 上是正确的,为什么当我运行我的应用程序时,spring 不填充 ${MYENV:local} 上的变量,我需要进行更多配置吗?

  2. 我开始使用微服务,因此如果我有多个微服务,这种设置环境变量的方式将很难维护。有没有更容易配置配置文件而无需发送命令行的方法?

最佳答案

您可以通过以下不同方式设置配置文件:

1)使用application.properties:

spring.profiles.active=dev

2)使用@Profile注释:

@Configuration
@Profile({ "profile1", "profile2" })
public class Test {

  @Bean
  public Employee employee() {
    ...
  }
}

3)使用maven:

<profile>
        <id>production</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <activeProfile>production</activeProfile>
        </properties>
    </profile>

4)使用 vmargument 我们可以这样做:

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

5)使用System.setProperty():

System.setProperty("spring.profiles.active", "dev");

6) 通过实现WebApplicationInitializer

@Configuration
public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        servletContext.setInitParameter("spring.profiles.active", "dev");
    }
}

7) 使用 web.xml:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/app-config.xml</param-value>
</context-param>
<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>dev</param-value>
</context-param>

关于java - 如何使用 Spring Boot 和 Maven 设置配置文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52004886/

相关文章:

java - 在中央找不到 Maven Artifact

java - XText:7 种语言教程无法解析示例 1 脚本中对 JvmIdentifyingElement 的引用

java - 在 JavaFX 中实现只读样式?

java - 为什么这么多方法使用 Collection 而不是 Iterable?

java - 使用 javax.xml 添加新 POJO 时出现 ClassCastException

java - 无法导入 GraphDatabaseFactory

java - 在 Json 中保留一些字段 - Java

java - 如何在 Linux 上使用 SIGAR 和 maven?

spring - Spring 基于注释的验证中的和/或条件

java - 如何从基于 Spring security 的应用程序创建访问表?