So, I got this class that belongs to a external library (so I can't modify it):
@Configuration
@EnableWebMvc
@Slf4j
public class WebConfigParent implements WebMvcConfigurer {
private final ObjectMapper objectMapper;
public WebConfigParent(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new ResourceHttpMessageConverter());
converters.add(new StringHttpMessageConverter());
converters.add(new ByteArrayHttpMessageConverter());
converters.add(mappingJackson2HttpMessageConverter());
}
@Bean //this is the issue!
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
return new MappingJackson2HttpMessageConverter(objectMapper);
}
Now, my class:
@Configuration
public class WebConfigChild extends WebConfigParent {
public WebConfigChild(ObjectMapper objectMapper) {
super(objectMapper);
}
Fails because of:
The bean 'mappingJackson2HttpMessageConverter', defined in class path resource [../WebConfigParent], could not be registered. A bean with that name has already been defined in class path resource [../WebConfigChild.class] and overriding is disabled.
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
I know it's dangerous to use the override setting (which, by the way, works) but I have no idea on how to prevent this behavior! I tried re-defining the method in the child class like this:
@Bean(name="anotherMapper")
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
return super.mappingJackson2HttpMessageConverter();
}
but still the same error...why??
Since WebConfigParent
is annotated with @Configuration
, it will be created as an additional configuration class, even though it's extended by WebConfigChild
. You could exclude WebConfigParent
from component scanning.
Try adding something like:
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX, pattern = "*.WebConfigParent"))