Question

Suppose you need to dynamically (at runtime) get an instance of a subtype of a given type.

How would you accomplish that using Spring IoC?

Was it helpful?

Solution

You can also use @Profile to achieve similar functionality in a more declarative way.

@Configuration
@Profile("default")
public class TypeAConfig {
    @Bean
    public Type getType() {
        return new TypeA();
    }
}

@Configuration
@Profile("otherProfile")
public class TypeBConfig() {
    @Bean
    public Type getType() {
        return new TypeB();
    }
}

@Configuration
public class SysConfig {
    @Autowired
    Type type;       

    @Bean Type getType() {
        return type;
    }
}

You can then control which implementation to use by specifying the profiles that Spring should activate, e.g. with the spring.profiles.active system property. More information in the JavaDoc for Profile

OTHER TIPS

I've found the following is an easy way to do it.

@Component
public class SystemPreferences {
  public boolean useA() {...}
}

interface Type {....}

public class TypeA implements Type {
   @Autowired
   Other xyz;
}

public class TypeB implements Type {...}

@Configuration
public class SysConfig {
  @Autowired
  SystemPreferences sysPrefs;

  @Bean
  public Type getType() {
    if (sysPrefs.useA()) {
      //Even though we are using *new*, Spring will autowire A's xyz instance variable
      return new TypeA();
    } else {
      return new TypeB();
    }
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top