Issue
I know I'm not the first to have this problem, but I'm struggling to create multiple beans of the same type in Spring Boot 2.5.4.
My config:
@Configuration
public class MapperConfig {
@Bean("yamlMapper")
public ObjectMapper yamlMapper() {
return new ObjectMapper(new YAMLFactory());
}
@Bean("jsonMapper")
public ObjectMapper jsonMapper() {
return new ObjectMapper();
}
}
And my service class:
@Service
@RequiredArgsConstructor
public class MapperService {
@Qualifier("jsonMapper")
private final ObjectMapper jsonMapper;
@Qualifier("yamlMapper")
private final ObjectMapper yamlMapper;
}
The error is as follows:
No qualifying bean of type 'com.fasterxml.jackson.databind.ObjectMapper' available: expected single matching bean but found 2: yamlMapper,jsonMapper
I've tried the various combinations of @Bean, @Qualifier, etc. suggested in other SO posts and the docs, but I can't seem to find a way of making Spring autowire by name instead of type. Any help would be greatly appreciated!
SOLUTION:
As pointed out by Youssef, it's not the MapperService which is failing to find the right bean, it's Spring Boot's MappingJackson2HttpMessageConverterConfiguration class. We can't add annotations to that class, so need to resort to using @Primary in our config.
The context loads okay as follows:
@Configuration
public class MapperConfig {
@Bean
public ObjectMapper yamlMapper() {
return new ObjectMapper(new YAMLFactory());
}
@Bean
@Primary
public ObjectMapper jsonMapper() {
return new ObjectMapper();
}
}
@Service
@RequiredArgsConstructor
public class MapperService {
@Autowired
@Qualifier("jsonMapper")
private final ObjectMapper jsonMapper;
@Autowired
@Qualifier("yamlMapper")
private final ObjectMapper yamlMapper;
}
Solution
You need to add @Primary
annotation to one of your ObjectMapper
beans like that
@Primary
@Bean("jsonMapper")
Because if you are using Spring Boot, it is needed by Jackson
when trying auto configuration:
Parameter 0 of method mappingJackson2HttpMessageConverter in org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration required a single bean, but 2 were found:
But be careful also to as @M.Deinum comment: could also break stuff as this will also (partially) disable auto configuration for the ObjectMapper
Answered By - Youssef