Video in progress

Strong Junior 🌱 Spring

How does Spring name a bean, and what happens when two beans end up with the same name?

For @Component the name is the class name with a lowercase first letter (orderService); for @Bean it is the method name. If two names collide, Boot fails at startup by default (BeanDefinitionOverrideException).

📖 Answer

@Service class OrderService { }            // name: orderService
@Service("orders") class OrderService2 { } // name: orders

@Bean RestClient bankClient() { ... }      // name: bankClient

In practice this shows up in two situations:

  • two classes with the same name in different packages: uz.shop.billing.Mapper and uz.shop.catalog.Mapper both become mapper;
  • your own @Bean has the same name as a bean from a library.

Since Boot 2.1 bean overriding is off by default, so the log says this:

The bean 'mapper', defined in class path resource [...], could not be registered.
A bean with that name has already been defined ... and overriding is disabled.

The simplest fix is to give one of them an explicit name: @Component("catalogMapper"). Don't turn on spring.main.allow-bean-definition-overriding=true: which bean wins then depends on load order, and one day in another environment a different bean may win.