Spring Boot 中是否有最佳实践来记录用@ConfigurationProperties 注释的属性bean?

Is there a best practice in Spring Boot to log a properties bean annotated with @ConfigurationProperties?

希望你一切都好。 我开门见山:

我正在 Spring 引导应用程序中工作,使用 Spring AOP 来处理日志记录问题。 它工作正常,但今天我发现我需要从 @ConfigurationProperties 注释的 bean 中记录一些属性(至少用于调试目的)。

我尝试使用切入点来捕获 class 构造函数及其设置器(Spring 用于通过反射填充字段)。它没有用,我认为这是由于反射使用造成的。

我使用以下代码解决了日志记录问题:

@Configuration
@Getter
@Setter
@ConfigurationProperties(prefix = "my.props")    
@Slf4j
public class MyProps {
    private String url;
    private String tableName;

    @PostConstruct
    void logSomeFields() {
        if (log.isInfoEnabled()) {
            log.info("The URL is '{}' and the table name is '{}'",
                url,
                tableName
            );
        }
    }
}

application.yml:

my:
  props:
    url: "http://localhost:8500"
    tablename: "test_table"

因为我认为将日志记录代码放在 属性 bean 中是一种不好的做法, 你能告诉我是否有使用 Spring AOP 的方法,这样我就可以将日志代码移出这个 class?

提前致谢。

此致!

您真正想要记录的似乎是服务对象的配置,因此请直接在对象的构造函数中执行此操作。通常在 DEBUG 或有时甚至是 TRACE 级别记录此信息,然后将日志语句保留在适当的位置,以便以后需要时可以打开它们。

请注意,没有必要使用 log.is<Level>Enabled,除非传递到方法调用中的项的计算成本很高;这就是首先使用 {} 特性而不是字符串连接的全部原因,以及为什么你不应该使用 toString() 而是让记录器在它决定需要时这样做。