Spring Bean Naming Using Software Configuration

When I define a bean definition using the XML configuration, I do not need to enter a name, for example:

<beans>
  <bean class="foo.Bar" />
  <bean class="foo.Bar" />
</beans>

The names will be internally given somehow foo.bar$1(or something like that, I don’t have an exact scheme right now).

However, when I define beans using the Java configuration, the name is implicitly inferred from the name of the annotated method:

@Configuration
public class DummyConfiguration {

  @Bean
  public Bar bar1() {
    return new Bar();
  }

  @Bean
  public Bar bar2() {
    return new Bar();
  }

}

Here beans are called bar1and bar2.

Now that I have a modular application structure where several configurations contribute to one application context, I don’t see a way to create multiple instances Bar, making sure that it does not overwrite another.

For example, one part of my application defines the following configuration:

@Configuration
public class ConfigurationForModuleA {

  @Bean
  public FooManager fooManager() {
    return new FooManagerImpl();
  }

  @Bean
  public SomeListener someListener() {
    return new FooSomeListener();
  }

}

( ) :

@Configuration
public class ConfigurationForModuleB {

  @Bean
  public BarManager barManager() {
    return new BarManagerImpl();
  }

  @Bean
  public SomeListener someListener() {
    return new BarSomeListener();
  }

}

, SomeListener, SomeListener, .

Spring bean? , @Bean("explicitName"), . - bean, , . XML Spring , Java?

+3
1

Spring bean?

: .

, BeanNameGenerator , , -, bean BeanNameGenerator beans, @Configuration (, , Spring 3.2.x Spring 4.0.x).

ConfigurationClassBeanDefinitionReader ( 184), , bean -coded; , , @Bean, .

+2

All Articles