以编程方式在 JpaProperties 中添加休眠拦截器 - Spring

Programmatically adding hibernate interceptor in JpaProperties - Spring

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

我想避免提供我自己的 sessionFactory bean,我认为最好将这种可能性留给一个实施项目,同时也让我免于手动扫描实体。

我的 愚蠢 想法是我可以 "inject" 我的拦截器进入 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
            );
}

由于这是使用 @PostConstruct 注释,因此 JpaProperties 的添加只会在 JpaBaseConfiguration 中创建 EntityManagerFactoryBuilder 之后发生。这意味着在此之后对 属性 地图的更改将不会出现在构建器中。

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

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

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