我有 2 个环境来设置我的 API,所以我有生产环境和开发环境。我首先需要找到一种自动执行此操作的方法,例如,在运行时无需发送任何参数(-D),应用程序找到一种方法来识别环境是谁,但我没有找到任何方法可以执行此操作这边走。
所以我读了一个教程,同样有一种方法来放置环境变量,并定义我的application.properties。因此,按照以下步骤:
我在应用程序中定义了 3 个文件:application.properties、application-dev.properties 和 application-prod.properties。
在 application.properties 中,我有配置 spring.profiles.active=${MYENV:local}。
在 application-dev.properties 中我有 spring.profiles.active=dev。
在 application-prod.properties 中我有 spring.profiles.active=prod。
我知道如果我传递命令 mvn spring-boot:run -Dspring-boot.run.profiles=(PROFILE) Spring 会完美选择配置文件。
我有两个问题:
我的环境变量在 Windows 上是正确的,为什么当我运行我的应用程序时,spring 不填充 ${MYENV:local} 上的变量,我需要进行更多配置吗?
我开始使用微服务,因此如果我有多个微服务,这种设置环境变量的方式将很难维护。有没有更容易配置配置文件而无需发送命令行的方法?
最佳答案
您可以通过以下不同方式设置配置文件:
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/