[英]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).我正在用 spring boot 编写一个库,我需要通过它以编程方式插入一个休眠拦截器(因为我不能在库中使用
.properties
)。
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.我想避免提供我自己的
sessionFactory
bean,我认为将这种可能性留给实施项目会很好,这也使我免于手动扫描实体。
My dumb idea was that I could "inject" my interceptor into the JpaProperties
.我
愚蠢的想法是我可以将我的拦截器“注入”到JpaProperties
。 That didn't work at all, it ran the @PostConstruct
but nothing changed.那根本不起作用,它运行了
@PostConstruct
但没有任何改变。 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
.由于这是使用
@PostConstruct
注释时,除了JpaProperties
后才会发生EntityManagerFactoryBuilder
已被创建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:要自定义
JpaProperties
,您应该实例化一个添加配置的 bean,例如:
@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
.然后将其注入
HibernateJpaConfiguration
并在构造EntityManagerFactoryBuilder
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.