Accessing Spring Beans inside AttributeConverter class

后端 未结 3 1407
逝去的感伤
逝去的感伤 2020-12-10 02:25

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

3条回答
  •  失恋的感觉
    2020-12-10 03:03

    You can inject a bean(@Component, @Service, @Repository) inside an AttributeConverter using static properties

    Setps:

    1. Set in your AttributeConverter with the following annotations: @Component, @Converter and @Configurable
    2. Define the field that you want to autowired with the static modifier access
    3. Create an init method in order to autowired the repository
    4. Implement the methods defined in the interface AttributeConverter

    Basically, the code should look like this...

    //Step 1
    @Component
    @Converter
    @Configurable
    public class MyAttributeConverter implements AttributeConverter {
        //Where: X = the type of the entity attribute and Y = the type of the database column
    
        //Step 2
        private static MyRepository myRepository;
    
        //Step 3
        @Autowired
        public void initMyRepository(MyRepository myRepository){
            MyAttributeConverter.myRepository = myRepository;
        }
    
        //Step 4
        Y convertToDatabaseColumn(X attribute){//TODO implement method}
        X convertToEntityAttribute(Y dbData){//TODO implement method}
    }
    

    I hope it can help!!!

提交回复
热议问题