【问题标题】:Is there a best practice in Spring Boot to log a properties bean annotated with @ConfigurationProperties?Spring Boot 中是否有记录使用 @ConfigurationProperties 注释的属性 bean 的最佳实践?
【发布时间】:2020-10-26 23:33:28
【问题描述】:

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

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

我尝试使用切入点来捕获类构造函数及其设置器(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,以便我可以将日志记录代码移出这个类吗?

提前谢谢你。

问候!

【问题讨论】:

    标签: java spring-boot logging properties spring-aop


    【解决方案1】:

    看来您真正要记录的是服务对象的配置,所以直接在对象的构造函数中进行。通常在 DEBUG 甚至 TRACE 级别记录这些信息,然后将日志语句保留在原处,以便以后需要时可以打开它们。

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

    【讨论】:

    • 有意思,之前没弄明白。谢谢!!
    猜你喜欢
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 2011-03-09
    • 1970-01-01
    • 2020-03-08
    • 2019-05-27
    • 2022-01-07
    相关资源
    最近更新 更多