Spring 启动 :Different configurations for running locally vs deployed Jar?

标签 spring spring-boot gradle

所以我有一个使用 jar 部署在 Amazon Web Services 上的 Spring Boot 应用程序,我还使用 IntelliJ 中的“Boot Run”在本地运行程序进行测试
当我在本地使用 bootrun 运行程序以及从云中的 jar 部署程序时,我只想更改程序运行方式的两件事。

在我的 app.properties 中,我设置了 4 个与在 redis 集群中存储 sessin 数据相关的属性,并且我在 java @Configuration 类中有一个与配置 redis 相关的 @Bean。我该如何设置它,以便当我在本地运行 Spring 会忽略这 4 个属性和 java bean,但在我部署时包含它们?

最佳答案

您可以为此使用 Spring 配置文件。您可以使用特定配置文件有条件地覆盖属性和加载类。

您的 application.properties default 默认加载文件轮廓。假设您要覆盖您的 Redis 配置实体。只需在资源文件夹中添加一个名为 application-redis.properties 的文件即可并编写要覆盖的属性。然后使用参数 --spring.profiles.active=redis 运行您的应用程序在命令行上(如果您使用的是 maven,它将是 -Dspring.profiles.active=redis ,我不知道 Gradle 是否是这种情况),或者添加到您的 application.propertiesspring.profiles.active=redis避免争论。如果您构建 jar,这也适用。

例子:

#application.properties

some.config=some-value

#application-redis.properties

#this value takes precedence if you run with the profile "redis" active
some.config=other-value

然后,加载特定的 @Configuration您添加的类(或任何其他 Spring 注入(inject)类)@Profile注释如:
@Profile("redis")
@Configuration
public class SomeConfigurationClass {
  //...
}

然后,只有当您使用“redis”事件配置文件运行应用程序时,才会加载此配置类。您可以阅读文档以获取更多信息:

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html

关于 Spring 启动 :Different configurations for running locally vs deployed Jar?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50044696/

相关文章:

java - Spring Cloud 配置无法加载 native 配置文件,除非文件名是 application

java - 本地主机和暂存 url 的 Cors 过滤器

security - Spring Boot - 仅保护执行器端点

java - 如何使模块 x 的第 3 方依赖项与其一起到达依赖于模块 x 的模块 y 的类路径?

java - 在gradle依赖项和Java项目中导入AWS Textract

Spring Boot 验证不适用于 javax.validation

java - spring Kafka ConsumerFactory bean 未找到

java - @PostConstruct 和 @PreDestroy 注解的实时应用程序使用

tomcat - 使用netbeans将gradle war部署到Tomcat中

java - Spring RestTemplate GET 请求删除空查询参数