'Autowiring inside jackson serializer if used by RestTemplate

I have an @Autowired in one of my Serializers which extends StdSerializer

public class RefSerializer extends StdSerializer<LabeledElement> {

    @Autowired
    I18n i18n;

    public RefSerializer() {
        this(null);
    }

    public RefSerializer(Class<LabeledElement> t) {
        super(t);
    }

    @Override
    public void serialize(LabeledElement element, JsonGenerator generator, SerializerProvider provider) throws IOException {
        String identifier = null;
        String label = LabelUtils.labelPlanElement(this.i18n, planElement, "ref");

        generator.writeObject(ReferenceElement.of(element.getId(), label, identifier));
    }
}

and is used by @JsonSerialize inside the model class.

@JsonSerialize(contentUsing = RefSerializer.class)
@JsonDeserialize(contentUsing = PlanElementDeserializer.class)
@OneToMany(fetch = FetchType.EAGER)
private List<PlanElement> planElements;

If the Serializer is called inside my @RestComponent annotated endpoints the @Autowired is resolved and everything works fine for incoming and returned models.

Now I want to send the model actively via RestTemplate#exchange, but now the @Autowired inside the Serializer is null.

restTemplate.exchange(endpointUrl, httpMethod, new HttpEntity<>(planElement, authHeader), Map.class, authParameters);

Is there a way to get the autowiring to work for outgoing REST calls with RestTemplate?

Using Spring-boot 2.6.3, Java 17



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source