spring 在 application.properties 中使用 spring.profile.default 时启动不加载默认配置文件

spring boot not loading default profile while using spring.profile.default in application.properties

仅供参考:我发誓没有激活配置文件配置,例如 -D 或 运行 配置

目标

当应用程序在没有任何激活配置文件的情况下启动时,dev 配置文件默认激活。

问题

我已设置 spring.profile.default = dev ,我希望开发配置文件已激活。但事实并非如此。

我做了什么

Run Environment

Spring-引导版本:2.1.2 发布

What I'm referred

1) 如何在 Spring 引导应用程序中使用配置文件 - https://www.javacodegeeks.com/2019/07/profiles-spring-boot-application.html#respond

这是我所做的代码

/resources/application.properties

spring.profiles.default= dev

application.environment=This is a "Default" Environment

/resources/application-dev.properties

application.environment=This is a "dev" Environment
server.port= 8082

/ProfileController.java

@RestController
@RequestMapping("/v1")
public class ProfileController {

    @Value("${application.environment}")
    private String applicationEnv;

    @GetMapping
    public String getApplicationEnv(){
        return applicationEnv;
    }
}

结果

localhost/v1 => 这是一个 "Default" 环境

我发现默认配置文件已正确设置为 dev

这是我的 spring- 引导日志。

2019-10-16 23:17:02.926 INFO 64099 --- [ main] c.e.s.SpringbootdemoappApplication : No active profile set, falling back to default profiles: dev

为服务器端口添加另一个日志

2019-10-17 00:25:03.837 INFO 68318 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8083 (http)

我添加的原因是它似乎不是与注入相关的问题。

是时候结束这个问题了

我想要实现的第一个目标是更改默认配置文件。 从 spring 文档 (https://docs.spring.io/spring/docs/4.2.0.RELEASE/spring-framework-reference/htmlsingle/#beans-definition-profiles-default) 中,可以将默认配置文件更改为 application.properties.

中的设置 spring.profiles.default

但这似乎有点错误(感谢@Antoniosss)。即使我在 application.properties 中设置了它并且控制台显示 No active profile set, falling back to default profiles: dev。 但是 dev 配置文件仍未激活。

我发现 更改默认配置文件应该在加载之前完成 application.properties

这意味着如果 application.properties 中描述了更改默认配置文件,则为时已晚。(IDK 为什么,我无法弄清楚,因为 Spring 中有太多层 ... ) 如果使用 -Dspring.default.profile = dev 设置默认配置文件,它会正常工作。

来自 https://github.com/spring-projects/spring-boot/issues/1219:

You can't change the default profile by declaring it in a config file. It has to be in place before the config files are read.

您只配置了默认配置文件。 您需要设置一个活动配置文件,例如 spring.profiles.active=dev 在您的应用程序属性中。对于注入当前活动配置文件,

@Value("${spring.profiles.active}")
private String currentActiveEnv;

您将默认配置文件回退设置为 devspring.profiles.default=dev。如果你有 spring.profiles.active=someOtherProfile,你会 someOtherProfile 激活。

2019-10-16 23:17:02.926 INFO 64099 --- [ main] c.e.s.SpringbootdemoappApplication : No active profile set, falling back to default profiles: dev

此日志表明 dev 配置文件是活动的,因为您没有激活任何明确的配置文件。

问题是您在应用程序加载后传递此属性,您需要在应用程序启动时提供此 属性

将其作为 JVM args 传递

java -jar -Dspring.profiles.default=dev myproject.jar

作为环境变量传递

java -jar myproject.jar --spring.profiles.default=dev

系统变量

SPRING_PROFILES_DEFAULT=dev

请完成以下 link -

https://medium.com/@khandkesoham7/profiling-with-spring-boot-408b33f8a25f

那位朋友解释的很好

并按照以下命令验证或生成构建的命令

mvn -Ppreprod package -DskipTests clean verify