How to @autowire some bean into JsonSerializer?

后端 未结 3 1134
孤街浪徒
孤街浪徒 2020-12-08 07:22

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

3条回答
  •  悲&欢浪女
    2020-12-08 08:05

    We had the same problem with JsonSerializer and Spring autowiring. The solution that worked for us was to make two constructors. One for Spring which sets the dependency as a static field, and another one that is used by the Jackson initialisation.

    This works because the Spring dependency injection (autowiring) happens before Jackson initialises the serializer.

    @Component
    public class MyCustomSerializer extends JsonSerializer {
    
        private static IDesignService designService;
    
        // Required by Jackson annotation to instantiate the serializer
        public MyCustomSerializer() { }
    
        @Autowired
        public MyCustomSerializer(IDesignService designService) {
            this.designService = designService;
        }
    
        @Override
        public void serialize(String m, JsonGenerator gen, SerializerProvider s) {
            gen.writeObject(MyCustomSerializer.designService.method(..));
        }
    }
    

提交回复
热议问题