[英]Spring Boot Datasource annotated with ConfigurationProperties but the properties are not loaded
[英]Is there a best practice in Spring Boot to log a properties bean annotated with @ConfigurationProperties?
希望你一切都好。 我会直截了当地说 go:
我正在使用 Spring AOP 处理日志记录问题的 Spring 引导应用程序。 它工作得很好,但是今天我发现我需要从@ConfigurationProperties -annotated 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
);
}
}
}
应用程序.yml:
my:
props:
url: "http://localhost:8500"
tablename: "test_table"
由于我认为将日志记录代码放在属性 bean 中是一种不好的做法,你能告诉我是否有办法使用 Spring AOP,这样我就可以将日志记录代码移出这个 class 吗?
先感谢您。
问候!
看来您真正要记录的是服务 object 的配置,因此请直接在对象的构造函数中执行此操作。 通常在 DEBUG 甚至 TRACE 级别记录这些信息,然后将日志语句留在原处,以便以后需要时可以打开它们。
请注意,没有必要使用log.is<Level>Enabled
,除非传递给方法调用的项目计算成本很高; 这就是首先使用{}
功能而不是字符串连接的全部原因,以及为什么您不应该使用toString()
而是让记录器在它决定需要时这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.