Avi
Avi

Reputation: 21858

Import @Configuration in runtime

Let's say I have 2 spring @Configuration classes:

@Configuration
public class Config1 {
   @Bean
   public SomeInterface getSomeInterface() {
      return SomeImpl1;
   }
}


@Configuration
public class Config2 {
   @Bean
   public SomeInterface getSomeInterface() {
      return SomeImpl2;
   }
}

Usually in my root context class I would do something like this:

@Import(Config1.class)
@Configuration
public class RootConfig {
   ...
}

Of course, I could do the same with Config2.

But what if I would like to choose which of them to load on runtime and not using @Import. Something like:

@Configuration
public class RootConfig {
   @DynamicImports // Made-up annotation
   public void loadConfigs() {
      // Do some logic here that imports Config1 or Config2 dynamically by some parameters (for example, env param)
   }
}

Upvotes: 3

Views: 1155

Answers (2)

user5182503
user5182503

Reputation:

It seems to me, that you can do it only manually, when you have the reference to context. For example:

var diContext = new AnnotationConfigWebApplicationContext();
diContext.register(FirstConfig.class);
diContext.register(SecondConfig.class);
...

Another way is to create config class at runtime, as it is described in this answer.

Upvotes: 0

gipinani
gipinani

Reputation: 14408

You can use @Profile at configuration class level:

@Configuration
@Profile("dev")
public class DevConfig {
}

@Configuration
@Profile("prod")
public class ProdConfig {
}

Then you can activate your current profile in different ways. For example inside a test class:

@ActiveProfiles("dev")
public class DevIntegrationTest 

In this case you are setting current active profile to dev and only @Profile("dev") annotated class are loaded.

You can also set current active profile setting a parameter to jvm:

-Dspring.profiles.active="dev"

So continue to using your @Import, but only class with correct profile will be loaded.

Upvotes: 1

Related Questions