jpa Spring托管语句检查器

siv3szwd  于 2023-02-16  发布在  Spring
关注(0)|答案(1)|浏览(136)

bounty将在14小时后过期。回答此问题可获得+50声望奖励。CDO希望引起更多人关注此问题。

如何创建一个“Spring托管的”StatementInspector来启用某些Springboot功能,如Autowiring类,并通过StatementInspector类中的@Value引用Spring属性。
我当前使用的通过配置属性注册StatementInspector的方法(如下所示)不支持这些Spring功能。

spring:
 jpa:
  properties:
   hibernate:
    session_factory:
      statement_inspector: x.x.SqlStatementInspector
pprl5pva

pprl5pva1#

可能的解决方案:
1.配置HibernatePropertiesCustomizer -bean

@Bean
public HibernatePropertiesCustomizer hibernateCustomizer(StatementInspector statementInspector) {
    return (properties) -> properties.put(AvailableSettings.STATEMENT_INSPECTOR, statementInspector);
}

1.根据属性值提供一个或多个conditionalStatementInspector-bean。

  • 示例 *:OneStatementInspector仅在演示语句检查器等于时创建
@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
        ...
    }

}
  • 应用程序.属性 *
demo.my-value=my autowired value
demo.statement_inspector = one

1.如果StatementInspector的配置是可选的(demo. statement_inspector不是强制的),则有多个选项:

  • 将可能的StatementInspector之一设为默认值(如果缺少属性,则匹配)@ConditionalOnProperty(prefix = "demo", name ="statement_inspector", havingValue = "...", matchIfMissing = true )
  • HibernatePropertiesCustomizer-bean设置为可选:
@Bean
@ConditionalOnProperty("demo.statement_inspector")
public HibernatePropertiesCustomizer hibernateCustomizer(StatementInspector statementInspector) {
    ...
}
  • 按照@dekkard的建议提供一个默认bean:
@Bean   
@ConditionalOnMissingBean(StatementInspector.class)     
public StatementInspector emptyInspector() {        
  return EmptyStatementInspector.INSTANCE;  
}
    • 注:**不需要设置spring.jpa.properties.hibernate.session_factory.statement_inspector

相关问题