java - @Profile 在没有 Spring Boot 的情况下不起作用(-Dspring.profiles.active 与 maven)
问题描述
在没有 Spring Boot 的情况下,我无法@Profile
使用 Maven 进行工作。在 pom.xml 中,我定义了 maven 配置文件(“env”和“dev”,这也是默认的)。
不幸的是,每当我尝试使用以下方式构建项目时:
mvn clean install -Dspring.profiles.active=env
始终应用“默认”配置文件(在 Spring - maven 应用“env”用于 maven 目的)。我也试图让它与它一起工作System.getProperty("spring.profiles.active")
,System.getenv("spring.profiles.active")
但那些总是返回 null。我认为还值得一提的是,这是非 Web 应用程序。
Beans(读取正确的属性):
@Bean
@Profile({"default"})
public static PropertySourcesPlaceholderConfigurer defaultProperties() {
return getPropertySourcesPlaceholderConfigurer("db.yml");
}
@Bean
@Profile({"env"})
public static PropertySourcesPlaceholderConfigurer envProperties() {
return getPropertySourcesPlaceholderConfigurer("db-env.yml");
}
@Bean
@Profile({"test"})
public static PropertySourcesPlaceholderConfigurer devProperties() {
return getPropertySourcesPlaceholderConfigurer("db-test.yml");
}
private static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer(String resource) {
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
yaml.setResources(new ClassPathResource(resource));
final Properties object = yaml.getObject();
if (object != null) {
propertySourcesPlaceholderConfigurer.setProperties(object);
}
return propertySourcesPlaceholderConfigurer;
}
Pom.xml:
<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
<property>
<name>spring.profiles.active</name>
<value>dev</value>
</property>
</activation>
</profile>
<profile>
<id>env</id>
<activation>
<property>
<name>spring.profiles.active</name>
<value>env</value>
</property>
</activation>
</profile>
</profiles>
解决方案
Spring 配置文件用于运行您的应用程序,而不是构建。-Dspring.profiles.active=env
执行应用程序时传递。在您的示例中,您正在执行mvn install
不执行您的应用程序的操作。
推荐阅读
- c - C编程中如何获取文本文件的第三列
- html - Bootstrap carousel - 在更改设备高度和宽度时防止图像被裁剪
- javascript - 箭头函数的另一个引人注目的用例是什么?
- snowflake-cloud-data-platform - 从 Tidal 调度器调度雪花脚本
- c++ - 为什么我在使用 void 函数时收到错误代码 C2276?
- python - 如何从 cloudwatch 事件中获取存储桶名称?
- amazon-redshift - 错误:由于内部错误,不支持这种类型的相关子查询模式
- php - Laravel 6 - 以 http 而不是 https 为前缀的资源链接
- websocket - Nexmo Voice api,带有 websockets 和用于语音翻译的 azure 认知服务
- perl - 在 VS2013/VS2019 Post Build Event 中运行 perl 的技巧