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
If the RestTemplate is provided by bean inside a @Configuration file like so:
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
and then autowired via @Autowired inside the service which uses the RestTemplate and not instantiated by "new RestTemplate()" the autowired services inside the custom serializer are also available for the RestTemplates REST calls.