Search code examples
springhibernatejpajdbc

Spring managed StatementInspector


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

Solution

  • A possible solution:

    1. Configure a HibernatePropertiesCustomizer-bean
    @Bean
    public HibernatePropertiesCustomizer hibernateCustomizer(StatementInspector statementInspector) {
        return (properties) -> properties.put(AvailableSettings.STATEMENT_INSPECTOR, statementInspector);
    }
    
    1. Provide a or more conditional 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
    
    1. If the configuration of a 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) {
        ...
    }
    
    • Provide a default bean as @dekkard suggests:
    @Bean   
    @ConditionalOnMissingBean(StatementInspector.class)     
    public StatementInspector emptyInspector() {        
      return EmptyStatementInspector.INSTANCE;  
    }
    

    note: No need to set spring.jpa.properties.hibernate.session_factory.statement_inspector