Search code examples
javaspringspring-mvcjackson

How to @autowire some bean into JsonSerializer?


I am using lazy loading with hibernate in my web app.

I would like to load some objects from the database at the parsing stage of the server response

@Component
public class DesignSerializer extends JsonSerializer<Design> {
@Autowired
IDesignService designService; <-- is null

}

Which is totally understandable because DesignSerializer is being instantiated with the "new" operator for each object.

I am sure there is a way to inject my bean into that serializer when ever it is created, I just don't know how.

Can you guys help me or point me in the right direction.


Solution

  • Solution is SpringBeanAutowiringSupport if you are using Spring Framework 2.5+.

    public class DesignSerializer extends JsonSerializer<Design> {
    
        @Autowired
            IDesignService designService;
        }
    
        public DesignSerializer(){
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);    
        }
    
    ...
    
    }
    

    I Hope that help you