Spring Boot服务未能获取由git-commit-id Maven插件生成的git.properties文件。

huangapple go评论52阅读模式
英文:

Spring Boot service is not picking up the git.properties file generated by the gi-commit-id maven plugin

问题

我已经将git-commit-id插件配置如下:

<plugin>
    <groupId>io.github.git-commit-id</groupId>
    <artifactId>git-commit-id-maven-plugin</artifactId>
    <version>6.0.0</version>
    <executions>
        <execution>
            <id>get-the-git-infos</id>
            <goals>
                <goal>revision</goal>
            </goals>
            <phase>initialize</phase>
        </execution>
    </executions>
    <configuration>
        <generateGitPropertiesFile>true</generateGitPropertiesFile>
        <includeOnlyProperties>
            <generateGitPropertiesFilename>${project.build.outputDirectory}/git.properties</generateGitPropertiesFilename>
            <includeOnlyProperty>^git.build.(time|version)$</includeOnlyProperty>
            <includeOnlyProperty>^git.commit.id.(abbrev|full)$</includeOnlyProperty>
            <includeOnlyProperty>^git.dirty$</includeOnlyProperty>
        </includeOnlyProperties>
        <commitIdGenerationMode>full</commitIdGenerationMode>
    </configuration>
</plugin>

它按预期工作并生成以下的git.properties文件:

#Generated by Git-Commit-Id-Plugin
git.build.time=2023-07-13T14:04:21+0200
git.build.version=5.0-SNAPSHOT
git.commit.id.abbrev=753455c
git.commit.id.full=753455c7ae51f231cefda280e0508feeb3655f59
git.dirty=true

一切正常!该文件保存在target/classes/git.properties中。

我创建了以下PropertySourceConfig.java文件以导入来自git.properites的属性:

package com.my.app.metrics;

import org.springframework.context.annotation.Bean;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

/**
 * Generates beans with access to properties required for metrics
 */
@Component
public class PropertySourceConfig {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        PropertySourcesPlaceholderConfigurer propsConfig
                = new PropertySourcesPlaceholderConfigurer();
        propsConfig.setLocation(new ClassPathResource("git.properties"));
        propsConfig.setIgnoreResourceNotFound(true);
        propsConfig.setIgnoreUnresolvablePlaceholders(true);
        return propsConfig;
    }
}

这有效,我已经在我的控制器之一中添加了带有@Value()注释的字段,指向git.properties中的属性,并且在运行调试器时可以看到这些字段中的正确值。

我还添加了以下的logback-spring.xml文件:

<configuration>
    <springProperty scope="context" name="applicationName" source="spring.application.name" defaultValue="unknown" />
    <springProperty scope="context" name="applicationVersion" source="project.version" defaultValue="unknown" />
    <springProperty scope="context" name="commitId" source="git.commit.id.abbrev" defaultValue="unknown" />

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="net.logstash.logback.encoder.LogstashEncoder">
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="CONSOLE" />
    </root>
</configuration>

这是我的问题开始的地方。

spring.application.name被如预期地捕获。
project.version(在application.properties中)也被捕获。
git.commit.id.abbrev(在git.properties中)没有被捕获,所以在日志输出中显示为“unknown”。

问题是什么?

我想说日志记录器在PropertySourceConfig对象创建之前被配置,因此在日志记录器启动时没有对它的引用。

如果是这样,我该如何修复?

也许我不能。也许策略应该是将此信息作为单独的度量标准添加,并将其直接推送到CloudWatch,而不是将其包含在日志中。

英文:

I have configured the git-commit-id plugin as follows:

    &lt;plugin&gt;
        &lt;groupId&gt;io.github.git-commit-id&lt;/groupId&gt;
        &lt;artifactId&gt;git-commit-id-maven-plugin&lt;/artifactId&gt;
        &lt;version&gt;6.0.0&lt;/version&gt;
        &lt;executions&gt;
            &lt;execution&gt;
                &lt;id&gt;get-the-git-infos&lt;/id&gt;
                &lt;goals&gt;
                    &lt;goal&gt;revision&lt;/goal&gt;
                &lt;/goals&gt;
                &lt;phase&gt;initialize&lt;/phase&gt;
            &lt;/execution&gt;
        &lt;/executions&gt;
        &lt;configuration&gt;
            &lt;generateGitPropertiesFile&gt;true&lt;/generateGitPropertiesFile&gt;
            &lt;includeOnlyProperties&gt;
                &lt;generateGitPropertiesFilename&gt;${project.build.outputDirectory}/git.properties&lt;/generateGitPropertiesFilename&gt;
                &lt;includeOnlyProperty&gt;^git.build.(time|version)$&lt;/includeOnlyProperty&gt;
                &lt;includeOnlyProperty&gt;^git.commit.id.(abbrev|full)$&lt;/includeOnlyProperty&gt;
                &lt;includeOnlyProperty&gt;^git.dirty$&lt;/includeOnlyProperty&gt;
            &lt;/includeOnlyProperties&gt;
            &lt;commitIdGenerationMode&gt;full&lt;/commitIdGenerationMode&gt;
        &lt;/configuration&gt;
    &lt;/plugin&gt;

It works as expected and generates the following git.properties file:

#Generated by Git-Commit-Id-Plugin
git.build.time=2023-07-13T14\:04\:21+0200
git.build.version=5.0-SNAPSHOT
git.commit.id.abbrev=753455c
git.commit.id.full=753455c7ae51f231cefda280e0508feeb3655f59
git.dirty=true

All good!
That file is saved in target/classes/git.properties.

I have created the following PropertySourceConfig.java file to import the properties from git.properites:

package com.my.app.metrics;

import org.springframework.context.annotation.Bean;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

/**
 * Generates beans with access to properties required for metrics
 */
@Component
public class PropertySourceConfig {


    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        PropertySourcesPlaceholderConfigurer propsConfig
                = new PropertySourcesPlaceholderConfigurer();
        propsConfig.setLocation(new ClassPathResource(&quot;git.properties&quot;));
        propsConfig.setIgnoreResourceNotFound(true);
        propsConfig.setIgnoreUnresolvablePlaceholders(true);
        return propsConfig;
    }
}

This works, I have added fields annotated with @Value() pointing at the properties in git.properties to one of my controllers, and can see the correct values in those fields when I run the debugger.

I have also added the following logback-spring.xml file:

&lt;configuration&gt;
    &lt;springProperty scope=&quot;context&quot; name=&quot;applicationName&quot; source=&quot;spring.application.name&quot; defaultValue=&quot;unknown&quot; /&gt;
    &lt;springProperty scope=&quot;context&quot; name=&quot;applicationVersion&quot; source=&quot;project.version&quot; defaultValue=&quot;unknown&quot; /&gt;
    &lt;springProperty scope=&quot;context&quot; name=&quot;commitId&quot; source=&quot;git.commit.id.abbrev&quot; defaultValue=&quot;unknown&quot; /&gt;

    &lt;appender name=&quot;CONSOLE&quot; class=&quot;ch.qos.logback.core.ConsoleAppender&quot;&gt;
        &lt;encoder class=&quot;net.logstash.logback.encoder.LogstashEncoder&quot;&gt;
        &lt;/encoder&gt;
    &lt;/appender&gt;

    &lt;root level=&quot;INFO&quot;&gt;
        &lt;appender-ref ref=&quot;CONSOLE&quot; /&gt;
    &lt;/root&gt;
&lt;/configuration&gt;

Here's where my problems start.

spring.application.name is picked up as expected.
project.version (in application.properties) is picked up too.
git.commit.id.abbrev (in git.properties) is not picked up, and so it shows up as "unknown" in the log output.

What is the issue here?

I want to say the logger is configured before the PropertySourceConfig object is created, and so there is no reference to it when the logger starts.

If so, how can I fix that?

Maybe I can't. Perhaps the strategy should be to add is info as a separate metric and push it directly to CloudWatch instead of including it in the logs at all?

答案1

得分: 2

git.properties 只能通过信息端点通过自动配置进行读取。它不是环境的一部分,因此不可用于属性替换。

要做到这一点,您需要确保它已加载。您可以使用以下两种方法之一:

  1. spring.config.import=classpath:/git.properties 添加到您的 application.properties 中。这应该会将其加载到 application.properties 旁边。

  2. 您可以编写一个 EnvironmentPostProcessor 来完成这个任务。

public class GitInfoAdder implements EnvironmentPostProcessor {

  public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    var gitResource = new ClasspathResource("git.properties");
    environment.getPropertySources().addLast(new ResourcePropertySource(gitResource));
  }
}

接下来,您需要在 src/main/resources/META-INF 目录中添加一个 spring.factories,以加载此 EnvironmentPostProcessor

org.springframework.boot.env.EnvironmentPostProcessor=your.package.GitInfoAdder

这也将添加属性。但我建议选择选项1,这可能是最简单的方法(也是我经常忘记的方法)。

英文:

The git.properties is read only by the info endpoint through the auto configuration. It isn't part of the environment and as such not available for property substitution.

To do this you would need to make sure it is loaded. You can use one of 2 approaches for this.

  1. add spring.config.import=classpath:/git.properties to your application.properties. This should load it next to the application.properties.

  2. You can write an EnvironmentPostProcessor to do this.

public class GitInfoAdder implements EnvironmentPostProcessor {

  public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    var gitResource = new ClasspathResource(&quot;git.properties&quot;);
    environment.getPropertySources().addLast(new ResourcePropertySource(gitResource));
  }
}

Next you need to add a spring.factories to your src/main/resources/META-INF directory to load this EnvironmentPostProcessor.

org.springframework.boot.env.EnvironmentPostProcessor=your.package. GitInfoAdder

This will add the properties as well. But I would suggest option 1 that is probably the easiest (and the one I keep forgetting).

huangapple
  • 本文由 发表于 2023年7月13日 20:23:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76679347.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定