在AttributeConverter类中访问Spring Bean [英] Accessing Spring Beans inside AttributeConverter class
问题描述
我正在开发Spring Data JPA应用程序,并且创建了一个AttributeConverter
类,以便将对象的ArrayList
作为JSON保存在数据库列中.在该类中,我需要使用已定义为Spring Bean的类.
I'm developing a Spring Data JPA application, and I've created an AttributeConverter
class in order to save an ArrayList
of objects as JSON in a database column. Inside this class I need to make use of a class I have defined as a Spring Bean.
由于AttributeConverter
类由Hibernate管理,因此它似乎在创建任何Spring Bean之前就已实例化,因此DI似乎不起作用(AttributeConverter
类中的Spring Bean是null
,并且我正在抛出NullPointer
异常).因此,目前我正在创建所述bean的另一个实例,以便能够在AttributeConverter
类中使用它(这违反了DI的目的).
As the AttributeConverter
class is managed by Hibernate, it seems to be instantiated before any Spring beans are created, and therefore DI does not seem to work (the Spring Bean in the AttributeConverter
class is null
, and I'm getting a NullPointer
exception thrown). So at the moment I'm creating another instance of the said bean to be able to use it in the AttributeConverter
class (which defeats the purpose of DI).
我还尝试创建一个实现ApplicationContextAware
的Util类(用@Component
注释),该类提供了提供SpringBean(cxt.getBean(BeanClass.class)
)的方法.但这也在AttributeConverter
之后的之后被实例化.
I've also tried creating a Util class (annotated with @Component
) which implements ApplicationContextAware
, which provides a method giving the SpringBean (cxt.getBean(BeanClass.class)
). But this also is instantiated after the AttributeConverter
.
对如何解决这个问题有任何想法吗?
Is there any idea of how this can be solved?
谢谢.
推荐答案
使用JPA 2.2,Spring 5.1( SPR-16305 )和Hibernate 5.3.0(
With JPA 2.2, Spring 5.1( SPR-16305) and Hibernate 5.3.0 (HHH-12135) you no longer need to use the mutable static property hack and can use dependency injection just like you would on a regular spring managed bean (note that annotations are no longer necessary):
public class MyAttributeConverter implements AttributeConverter<X,Y> {
private final MySpringBean bean;
public MyAttributeConverter(MySpringBean bean) {
this.bean = bean;
}
public Y convertToDatabaseColumn(X attribute) {
...
}
public X convertToEntityAttribute(Y dbData) {
...
}
}
这篇关于在AttributeConverter类中访问Spring Bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!