Java ValueInjector-class And Method Code Example

Here is an example of a custom ValueInjector class in Java using the com.fasterxml.jackson.databind package:

import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ValueInjector extends InjectableValues.Std {

    public Object findInjectableValue(Object valueId, DeserializationContext ctxt, BeanProperty forProperty, Object beanInstance) {
        if ("customValue".equals(valueId)) {
            // return custom value
            return "injectedValue";
        return super.findInjectableValue(valueId, ctxt, forProperty, beanInstance);

In this example, ValueInjector is a custom implementation of the InjectableValues class. It overrides the findInjectableValue method to provide custom logic for injecting a specific value identified by the valueId parameter.

You can use this custom injector by registering it with the ObjectMapper:

ValueInjector injector = new ValueInjector();
ObjectMapper mapper = new ObjectMapper();

When deserializing, if the JSON contains "{customValue: ...}" the findInjectableValue method will be called and injectedValue will be injected in the target object.