所以我有一个使用 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.properties
行spring.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/