Is there a way to inject dependencies into POJOs supplied by Spring RestControllers? For example, if you wanted to implement polymorphic behavior.
The following example fails with a NullPointerExcetion
because lowerCaseService
is not injected into the Example
POJO:
@RestController
public class ExampleController {
@PostMapping("/example")
String example(@RequestBody Example example) {
return example.valueToLowerCase();
}
}
@Data
@NoArgsConstructor
public class Example {
private String value;
@Autowired
private LowerCaseService lowerCaseService;
public String valueToLowerCase() {
return lowerCaseService.toLowerCase(getValue());
}
}
@Service
public class LowerCaseService {
public String toLowerCase(String value) {
return value != null ? value.toLowerCase() : null;
}
}
Note that this contrived example is intentionally simple and doesn't need polymorphic behavior. I created it this way to help responders make quick sense of it and not get bogged down by Jackson's annotations. In my actual use case Jackson will produce subclasses of Example
, where each needs to do very different things, with different dependencies.