Search code examples
springspring-ioc

Spring Ioc Beans management


I have a question about spring IoC management. I created Bean in:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {....}

    @Bean
    public XmlMapper xmlMapper() {
        return new XmlMapper();
    }
}

These beans work fine as expected. But Default ObjectMapper get overridden and
@RestController try to parse the request and expect that payload is XML.

Can anyone explain why this happens?


Solution

  • XmlMapper is a sub class of ObjectMapper so if you declare one bean of this type, Spring will use that one and inject it where needed.

    If you want to still use basic ObjectMapper elsewhere. You can declare another bean ObjectMapper. You may have to indicate it as primary.

    @SpringBootApplication
    public class Application {
        public static void main(String[] args) {....}
    
        @Bean
        public XmlMapper xmlMapper() {
            return new XmlMapper();
        }
    
        @Bean
        @Primary //Not sure if needed
        public ObjectMapper objectMapper() {
            return new ObjectMapper();
        }
    }