Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
755 views
in Technique[技术] by (71.8m points)

hibernate - Accessing Spring Beans inside AttributeConverter class

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.

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).

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?

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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) {
      ...
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...