spring-framework: Prevent @Bean method overloading by default (avoiding accidental overloading and condition mismatches)

Hello poeple,

I lost some hours configuring a bean with same id but different properties in java config, as the raised error message was not very helpful.

The bean in question must be created, as it is required via declarative @DependsOn configuration.

The error

A component required a bean named 'postgresqlContainer' that could not be found.
	- Bean method 'postgresqlContainer' in 'PersistenceConfig.DbServersConfig' not loaded because @ConditionalOnProperty (app.persistence.servers.postgresql.enabled=true) found different value in property 'enabled'
	- Bean method 'postgresqlContainer' in 'PersistenceConfig.DbServersConfig' not loaded because @ConditionalOnProperty (app.persistence.servers.postgresql.enabled=true) found different value in property 'enabled'

This config fails:

@Configuration
public class PersistenceConfig {

  @Configuration
  public class DbServersConfig {

    @Bean(value = "postgresqlContainer", initMethod = "start", destroyMethod = "stop")
    @ConditionalOnProperty(prefix = "app.persistence.servers.postgresql", name = "enabled", havingValue = "true")
    public PostgreSQLContainer postgresqlContainer(TCPostgresqlProperties postgresqlProperties) {
        Instance retVal = <do_your_logic>
        return retVal;
    }

    @Bean("postgresqlContainer")
    @ConditionalOnProperty(prefix = "app.persistence.servers.postgresql", name = "enabled", havingValue = "false", matchIfMissing = true)
    public PostgreSQLContainer postgresqlContainer() {
      return null;
    }
  }
}

This config works:

@Configuration
public class PersistenceConfig {

  @Configuration
  public class DbServersConfig {

    @Bean(value = "postgresqlContainer", initMethod = "start", destroyMethod = "stop")
    @ConditionalOnProperty(prefix = "app.persistence.servers.postgresql", name = "enabled", havingValue = "true")
    public PostgreSQLContainer  postgresqlContainer(TCPostgresqlProperties postgresqlProperties) {
        Instance retVal = <do_your_logic>
        return retVal;
    }

    @Bean("postgresqlContainer")
    @ConditionalOnProperty(prefix = "app.persistence.servers.postgresql", name = "enabled", havingValue = "false", matchIfMissing = true)
    public PostgreSQLContainer postgresqlContainer2() {
      return null;
    }
  }
}

If you name both methods differently (postgresqlContainer and postgresqlContainer2) then everything works as expected otherwise you get an error.

Is this desired behavior ?

I am unsure if my scenario could indicate a bug, too. I do not know if this problem happens only to @ConditionalOnProperty or any other condition like @ConditionalOnExpression.

Best regards

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 15 (7 by maintainers)

Most upvoted comments

I ended up introducing an enforceUniqueMethods flag on the @Configuration annotation, by default set to true. This prevents accidental overloading by enforcing distinct @Bean method names for separate bean definitions (which includes “alternative” bean definitions with mutually exclusive conditions). This can be switched to false for the previous lenient acceptance of overloaded methods as factory method candidates for the same bean definition.

All in all, the default behavior should provide better guidance now. The error message shown when rejecting same-named @Bean methods in 6.0 hints at the enforceUniqueMethods flag for whoever intends to opt into the overloading behavior, or whoever has existing configuration classes which happen to rely on the overloading.

@mbhave and @wilkinsona, thanks for the detective work!

I agree that the algorithm in question should take overloaded methods into account and thus track skipped methods based on each method’s name plus its formal parameter list.

Let’s see if the rest of the team agrees.

After a team discussion this morning, we are leaning towards a more radical step: disallowing overloaded @Bean methods completely, therefore raising an error in case of the same method name reappearing in any form. The original method overloading arrangement for factory methods was inspired by overloaded constructors, treated the same way by our constructor resolution algorithm. Unfortunately this causes more harm than good with @Bean methods where it is not obvious that all such same-named methods are part of the same bean definition, with all metadata expected to be equivalent. This was simply never meant to be used with mutually exclusive conditions, or any differing conditions to begin with.

The use cases for factory method overloading (just like with constructor overloading) are mostly related to optional arguments, with the “greediest satisfiable” factory method being calling, e.g. a variant with an optional argument, falling back to the overloaded method without the optional argument otherwise. In a modern-day Spring application, optional factory method arguments can be modeled in various forms, including @Nullable arguments and Optional<...> declarations, so there should not be any exclusive needs for factory method overloading anymore. That’s why we are considering to disallow it completely for Spring Framework 6.0, ideally as of the 6.0 M3 release already.

Enforcing a strict non-overloading rule for @Bean methods would prevent accidental overloading that cannot ever work properly, as well as half-accidental overloading that might work by chance but not really by design. For exclusive conditions (“alternative beans”), it is always preferable to use distinct bean names, no matter whether there are optional arguments involved or not. After all, alternative beans with the same (or no) arguments can only be modeled with distinct method names according to Java language rules; this is a strong indication that method overloading for exclusive conditions is misguided, only accidentally working if the method arguments happen to differ between the alternative definitions.