0

I am not sure how to register my custom objectMapper that I created below as a bean and inject it as dependency into other objects via constructor, or Autowire


@SpringBootApplication
public class DemoApplication {

@Bean
//how to register it as a bean here and inject wherever I need to via @Inject or @Autowire

public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}


@Provider
public class ObjectMapperProvider implements ContextResolver<ObjectMapper> {
    private final ObjectMapper objectMapper = new ObjectMapper();

    public ObjectMapperProvider() {
        this.objectMapper.disable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
    }

    @Override
    public ObjectMapper getContext(final Class<?> type) {
        return objectMapper;
    }
}

Lisa
  • 129
  • 1
  • 1
  • 8

1 Answers1

1

Be careful with that. You are mixing Jax-RS and Spring, but you have to know something: Spring does not implement fully the Jax-RS specification... The reason ? Spring MVC was developed about the same time as JAX-RS, and after JAX-RS was released, they never migrate to implement this (who would have anyway) ?

The best way to declare your own ObjectMapper with Spring would be the following:

@SpringBootApplication
public class DemoApplication {

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        // DO what you want;
        return objectMapper;
    }

    public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    }
}

Then, you can use @Autowired to inject your ObjectMapper in the class that needs it. (check this link if you want: Configuring ObjectMapper in Spring)

Hope it helps.

RUARO Thibault
  • 2,672
  • 1
  • 9
  • 14