如何@autowire一些bean进入JsonSerializer?

Gle*_*eeb 23 java spring spring-mvc jackson

我在我的网络应用程序中使用延迟加载与hibernate.

我想在服务器响应的解析阶段从数据库加载一些对象

@Component
public class DesignSerializer extends JsonSerializer<Design> {
@Autowired
IDesignService designService; <-- is null
Run Code Online (Sandbox Code Playgroud)

}

这是完全可以理解的,因为DesignSerializer每个对象都使用"new"运算符进行实例化.

我确信有一种方法可以在创建时将bean注入该序列化程序,我只是不知道如何.

你们能帮助我或指出我正确的方向吗?

Pet*_*vic 25

解决办法是SpringBeanAutowiringSupport如果你正在使用Spring框架2.5+.

public class DesignSerializer extends JsonSerializer<Design> {

    @Autowired
        IDesignService designService;
    }

    public DesignSerializer(){
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);    
    }

...

}
Run Code Online (Sandbox Code Playgroud)

我希望能帮助你

  • 真棒.与整个网络上的其他建议相比,这么简单. (2认同)

vei*_*set 15

我们遇到了与JsonSerializer和Spring自动装配相同的问题.对我们有用的解决方案是制作两个构造函数.一个用于Spring,它将依赖关系设置为静态字段,另一个用于Jackson初始化.

这是因为Spring依赖注入(自动装配)发生在Jackson初始化序列化程序之前.

@Component
public class MyCustomSerializer extends JsonSerializer<String> {

    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(..));
    }
}
Run Code Online (Sandbox Code Playgroud)