在AttributeConverter类中访问Spring Bean [英] Accessing Spring Beans inside AttributeConverter class

查看:160
本文介绍了在AttributeConverter类中访问Spring Bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆