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

时间:2019-04-04 13:54:46

标签: java spring hibernate interceptor

我正在用Spring Boot编写一个库,我需要以编程方式通过它插入一个休眠拦截器(因为我不能在lib中使用.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
            );
}

1 个答案:

答案 0 :(得分:1)

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

要自定义JpaProperties,应实例化一个将配置添加到其中的bean,例如:

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

然后将其注入HibernateJpaConfiguration中,并在构造EntityManagerFactoryBuilder时使用。