简体   繁体   English

如何@autowire一些bean进入JsonSerializer?

[英]How to @autowire some bean into JsonSerializer?

I am using lazy loading with hibernate in my web app. 我在我的网络应用程序中使用延迟加载与hibernate。

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. 这是完全可以理解的,因为DesignSerializer正在使用每个对象的“new”运算符进行实例化。

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. 我确信有一种方法可以在创建时将bean注入该序列化程序,我只是不知道如何。

Can you guys help me or point me in the right direction. 你们能帮助我或指出我正确的方向吗?

Solution is SpringBeanAutowiringSupport if you are using Spring Framework 2.5+. 解决办法是SpringBeanAutowiringSupport如果你正在使用Spring框架2.5+。

public class DesignSerializer extends JsonSerializer<Design> {

    @Autowired
        IDesignService designService;
    }

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

...

}

I Hope that help you 我希望能帮助你

We had the same problem with JsonSerializer and Spring autowiring. 我们遇到了与JsonSerializer和Spring自动装配相同的问题。 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. 一个用于Spring,它将依赖关系设置为静态字段,另一个用于Jackson初始化。

This works because the Spring dependency injection (autowiring) happens before Jackson initialises the serializer. 这是因为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(..));
    }
}

I Solved the problem by creating a static field in a different bean and then @Autowire its setter method. 我通过在另一个bean中创建静态字段然后@Autowire其setter方法解决了这个问题。

@Service("ToolBox")
@Transactional
public class ToolBox 
{
static Logger logger = Logger.getLogger(ToolBox.class);


private static IService service;


@Autowired
public void setService(IService service)
{
    ToolBox.service = service;
}

public static IService getService()
{
    return ToolBox.service;
}}

like shown in this thread: Can you use @Autowired with static fields? 如此线程所示: 你可以将@Autowired与静态字段一起使用吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM