![](/img/trans.png)
[英]Setting active profile and config location from command line in spring boot
[英]how to read active profile from different location in spring boot?
我在 src/main/resources 中有我的 application.properties 文件,并且在不同的目录中有不同的活动配置文件(application-dev.properties 和 application-prod.properties)作为 src/main/resources/properties。
我正在使用 springboot 版本 2.7.5
我试图在 directory-src/main/resources spring.profiles.active=dev 中的 application.properties 文件中配置它
但它没有从目录 src/main/resources/properties 中读取 application-dev.properties
为了解决这个问题,我创建了两个 class
@Configuration
public class ActiveProfileConfiguration extends AbstractSecurityWebApplicationInitializer{
private static final Logger log = LoggerFactory.getLogger(ApplicationJPAConfiguration.class);
private static final String SPRING_PROFILES_ACTIVE = "SPRING_PROFILES_ACTIVE";
String profile;
protected void setSpringProfile(ServletContext servletContext) {
if(null!= System.getenv(SPRING_PROFILES_ACTIVE)){
profile=System.getenv(SPRING_PROFILES_ACTIVE);
}else if(null!= System.getProperty(SPRING_PROFILES_ACTIVE)){
profile=System.getProperty(SPRING_PROFILES_ACTIVE);
}else{
profile="local";
}
log.info("***** Profile configured is ****** "+ profile);
servletContext.setInitParameter("spring.profiles.active", profile);
}
}
和
@Configuration
@Profile("local")
public class DevPropertyReader {
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
Resource[] resources = new ClassPathResource[] { new ClassPathResource("application.properties"), new ClassPathResource("EnvironmentProfiles/application-local.properties") };
ppc.setLocations(resources);
ppc.setIgnoreUnresolvablePlaceholders(true);
System.out.println("env active profile");
return ppc;
}
}
但是仍然无法解决这个问题。
Spring 不会在您的自定义/properties
文件夹中查找属性文件:
21.2 应用程序属性文件 SpringApplication将从以下位置的application.properties文件中加载属性,并将它们添加到Spring Environment中:
- 当前目录的 /config 子目录。
- 当前目录
- 一个配置 package
- 类路径根
最简单的解决方案是将其移动到src/main/resources
文件夹的根目录下。
Place.properties 结构如下:
src/
├─ main/
│ ├─ resources/
│ │ ├─ application.properties
│ │ ├─ application-dev.properties
│ │ ├─ application-prod.properties
下面的 Dockerfile 示例在运行您的应用程序时设置了正确的 Spring 配置文件:
ENTRYPOINT java -Dspring.profiles.active=prod -jar /app.jar
但是通过 WebApplicationInitializer、Beans XML、Maven 配置文件等还有许多其他选项...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.