【问题标题】:Programmatically adding hibernate interceptor in JpaProperties - Spring以编程方式在 JpaProperties - Spring 中添加休眠拦截器
【发布时间】:2019-08-26 07:34:52
【问题描述】:

我正在编写一个带有 Spring Boot 的库,我需要通过它以编程方式插入一个休眠拦截器(因为我不能在库中使用 .properties)。

我想避免提供我自己的sessionFactory bean,我认为将这种可能性留给实施项目会很好,也使我免于手动扫描实体。

我的愚蠢想法是我可以将我的拦截器“注入”到JpaProperties。那根本不起作用,它运行了@PostConstruct,但没有任何改变。我觉得这行不通,但我想了解原因,以及如何让它发挥作用。

@Autowired private JpaProperties properties;
@Autowired private MyInterceptor myInterceptor; //yep a bean

@PostConstruct public void add() {
    ((Map) properties.getProperties())
            .put(
                    "hibernate.session_factory.interceptor",
                    myInterceptor
            );
}

【问题讨论】:

    标签: java spring hibernate interceptor


    【解决方案1】:

    由于这是使用@PostConstruct 注释,所以只有在JpaBaseConfiguration 中创建了EntityManagerFactoryBuilder 之后才会对JpaProperties 进行添加。这意味着在此之后对属性映射的更改将不会出现在构建器中。

    要自定义JpaProperties,您应该实例化一个添加您的配置的bean,例如:

        @Primary
        @Bean
        public JpaProperties jpaProperties() {
            JpaProperties properties = new JpaProperties();
            properties.getProperties().put("hibernate.session_factory.interceptor", myInterceptor);
            return properties;
        }
    

    这将被注入HibernateJpaConfiguration 并在构造EntityManagerFactoryBuilder 时使用。

    【讨论】:

    • 提供我自己的 bean 不会覆盖 .properties 文件中的所有配置?我的意图只是覆盖hibernate.session_factory.interceptor
    • 构建自己的 JpaProperties 对象不会覆盖 .properties 文件或其他属性源中的配置值。配置 JpaProperties 对象时,对象上的 @ConfigurationProperties(prefix = "spring.jpa") 注释会导致将具有 spring.jpa.properties.hibernate.jdbc.fetch_size 等键的任何属性插入到属性映射中,而无需 spring.jpa.properties 前缀。
    • 那么这解决了 2 天前的头痛...谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多