简体   繁体   中英

Programmatically adding hibernate interceptor in JpaProperties - Spring

I'm writing a library with spring boot, and I need to programmatically insert a hibernate interceptor through it (because I can't use a .properties in a lib).

I want to avoid providing my own sessionFactory bean, I think it would be good to leave that possibility to an implementing project, also saves me from manually scanning for entities.

My dumb idea was that I could "inject" my interceptor into the JpaProperties . That didn't work at all, it ran the @PostConstruct but nothing changed. I had a feeling this wouldn't work, but I would like to understand why, and how I may get this to work.

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

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

As this is using an @PostConstruct annotation, the addition to the JpaProperties will only occur after the EntityManagerFactoryBuilder has been created in JpaBaseConfiguration . This means that changes to the property map will not be present in the builder after this point.

To customize the JpaProperties , you should instantiate a bean which adds your configuration in, like:

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

This will then be injected into HibernateJpaConfiguration and used when constructing the EntityManagerFactoryBuilder .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM