Home > OS >  Override name of inherited Bean
Override name of inherited Bean

Time:10-06

Is it possible to override the bean name of an inherited abstract class?

E.g. I got a abstract class with a Bean method. Now I want to set a specific name for the Bean if I extend it. Is this possible and how?

@Configuration
abstract class AbstractConfig {

  @Bean
  open fun foo(): Foo {
    // ....
  }

}
@Configuration
class myConfig: AbstractConfig() {

  @Bean("myFoo")
  override fun foo(): Foo {
    // ...
  }
}

CodePudding user response:

In the above example, when making Autowired/Inject you will always get the override implementation (you will never get the one in the abstract class). If you want to be able to get several implementations you can add several methods that creates Foo, each one will create another implementation and will have another bean name.

CodePudding user response:

To my knowledge, you can't do that. If you want to connect to multiple MongoDBs you need to create and register the Beans programmatically with GenericApplicationContext.registerBean() method. You can find more details about this at https://www.baeldung.com/spring-5-functional-beans.

  • Related