Search code examples
javaspring-bootjackson-databind

Error create @Bean of ObjectMapper in @Service


i have this configuration class:

@Configuration
public class ApplicationConfig {

    @Bean
    public ObjectMapper obMapper() {
        return new ObjectMapper();
    }

}

And this in my service:

@Qualifier("obMapper")
private ObjectMapper obMapper;

But i recieve this error:

Parameter 0 of method jacksonCodecCustomizer in org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration$JacksonCodecConfiguration required a single bean

How should i create it?


Solution

  • If you want to inject the bean you have to use one of these:

    1. Autowire the dependency

    @Autowired
    @Qualifier("obMapper")
    private ObjectMapper objectMapper;
    

    2. Use setter injection

    private ObjectMapper objectMapper;
    @Autowired
    public setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }
    

    You can find more details for example in this article on Baeldung.