How can I create a "Spring managed" StatementInspector to enable certain Springboot functionality like Autowiring
classes and referencing spring properties via @Value
within the StatementInspector
class.
The current method I use to register a StatementInspector via a configuration property (below) does not allow for these Spring functionalities.
spring:
jpa:
properties:
hibernate:
session_factory:
statement_inspector: x.x.SqlStatementInspector
A possible solution:
HibernatePropertiesCustomizer
-bean@Bean
public HibernatePropertiesCustomizer hibernateCustomizer(StatementInspector statementInspector) {
return (properties) -> properties.put(AvailableSettings.STATEMENT_INSPECTOR, statementInspector);
}
StatementInspector
-beans based on a property value.example: OneStatementInspector is only created when demo.statement_inspector is equal to one
@Component
@ConditionalOnProperty(prefix = "demo", name ="statement_inspector", havingValue = "one" )
public class OneStatementInspector implements StatementInspector {
@Value("${demo.my-value}") String myValue;
@Override
public String inspect(String s) {
// myValue is available here
...
}
}
application.properties
demo.my-value=my autowired value
demo.statement_inspector = one
StatementInspector
is optional ( demo.statement_inspector is not mandatory) there are multiple options:Make one of the possible StatementInspector
the default (match if property is missing) @ConditionalOnProperty(prefix = "demo", name ="statement_inspector", havingValue = "...", matchIfMissing = true )
Make HibernatePropertiesCustomizer
-bean optional:
@Bean
@ConditionalOnProperty("demo.statement_inspector")
public HibernatePropertiesCustomizer hibernateCustomizer(StatementInspector statementInspector) {
...
}
@Bean
@ConditionalOnMissingBean(StatementInspector.class)
public StatementInspector emptyInspector() {
return EmptyStatementInspector.INSTANCE;
}
note: No need to set spring.jpa.properties.hibernate.session_factory.statement_inspector