Hope you're doing fine. I'll go straight to the point:
I'm working in a Spring Boot application using Spring AOP for the logging concern. It works fine, but today I found that I need to log some properties from a @ConfigurationProperties-annotated bean (for debug purposes, at least).
I tried using a pointcut to capture the class constructor and its setters (which Spring uses to fill in the fields with reflexion). It didn't work and I believe that is due to that reflexion usage.
I solved the logging issue using the following code:
@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"
As I assume that putting logging code in a property bean is a bad practice, can you tell me if there's a way to use Spring AOP so I can move the logging code out of this class?
Thank you in advance.
Regards!
It appears that what you're really trying to log is the configuration of a service object, so do that directly, in the object's constructor. It's usual to log this information at DEBUG or sometimes even TRACE level, then leave the log statements in place so they can be turned on if needed later.
Note that it's not necessary to use log.is<Level>Enabled
unless the items that are passed into the method call are expensive to calculate; this is the whole reason for using the {}
feature instead of string concatenation in the first place, and why you shouldn't use toString()
but rather let the logger do that if it decides it needs to.