Home > Enterprise >  How can I refactor similar configuration classes in Spring Boot?
How can I refactor similar configuration classes in Spring Boot?

Time:01-26

I have multiple similar configuration classes in my project.

@Configuration
public class configA {
  private final static String CONFIG_STRING = "configA";

  @Bean( name = "first"   CONFIG_STRING )
  public First first() {
    ...
  }

  @Bean( name = "second"   CONFIG_STRING )
  public Second second() {
    ...
  }
}

@Configuration
public class configB {
  private final static String CONFIG_STRING = "configB";

  @Bean( name = "first"   CONFIG_STRING )
  public First first() {
    ...
  }

  @Bean( name = "second"   CONFIG_STRING )
  public Second second() {
    ...
  }
}

They're all the same, only the CONFIG_STRING is different.

Can I refactor those classes?

CodePudding user response:

You can use Template Method in order to let subclasses override specific steps of the algorithm without changing its structure.

Here is an example below. If there is a method that keeps the shared behaviour, this approach would also be a good option.


BaseConfig:

@Configuration
public abstract class BaseConfig {

    protected abstract String first();

    protected abstract String second();
}

ConfigA:

@Configuration
public class ConfigA extends BaseConfig {

    private final static String CONFIG_STRING = "configA";

    @Override
    @Bean( name = "first"   CONFIG_STRING )
    protected String first() {
        return CONFIG_STRING;
    }

    @Override
    @Bean( name = "second"   CONFIG_STRING )
    protected String second() {
        return CONFIG_STRING;
    }
}

ConfigB:

@Configuration
public class ConfigB extends BaseConfig {

    private final static String CONFIG_STRING = "configB";

    @Override
    @Bean( name = "first"   CONFIG_STRING )
    protected String first() {
        return CONFIG_STRING;
    }

    @Override
    @Bean( name = "second"   CONFIG_STRING )
    protected String second() {
        return CONFIG_STRING;
    }
}
  • Related