4

I am using Spring boot Multi-Module for my project. Problem here is that, I have 2 modules - Module A and Module B

Module A contains bean- moduleService.java

Module B contains bean- moduleService.java

Now while compiling I am getting error that Bean with the same name already exists. When I am working with 10 modules and using IDE to run a single module, can't keep track of name of bean in each module. Is there any solution for this?

Akash Kumar
  • 642
  • 7
  • 20
  • 1
    Well probably you cant, and only option is to use @Qualifier – user2377971 Apr 25 '19 at 07:43
  • The problem, I think is with the same name bean in the application context. You can qualify the beans by their name. – KumarAnkit Apr 25 '19 at 07:44
  • You have to keep track of the names, else you will run into the issue of one bean overriding the other without you knowing. Unless that is intended, but you would rather solve that in configuration. – M. Deinum Apr 25 '19 at 08:22
  • I read about giving a custom name to the bean with@Component("Name") and using @Qualifier to inject it, but its an overhead. – Akash Kumar Apr 26 '19 at 09:40

1 Answers1

0

Since you're seeing duplicate bean name exceptions I'll assume that you're using at least Spring Boot 2.1.0 because bean overriding is now an exception unless explicitly enabled with spring.main.allow-bean-definition-overriding = true.

The default bean naming strategy used by Spring Boot is for imported beans to be named using the fully qualified class name and for context-scanned beans to use just the short name. See source here.

Assuming that your beans are context-scanned and are therefore clashing on the short class name and not the fully qualified name then you can tell Spring Boot to use the fully-qualified naming strategy in your main class. Just copy the few lines of source code from the ConfigurationClassPostProcessor linked above:

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.util.Assert;

public static void main(String[] args) {

  new SpringApplicationBuilder(Application.class)
      .beanNameGenerator(new AnnotationBeanNameGenerator() {
        @Override
        protected String buildDefaultBeanName(BeanDefinition definition) {
          String beanClassName = definition.getBeanClassName();
          Assert.state(beanClassName != null, "No bean class name set");
          return beanClassName;
        }
      })
      .run(args);
}

This strategy will respect any bean naming directives provided by annotations that you have added to the beans.

Andy Brown
  • 11,766
  • 2
  • 42
  • 61