Mital Pritmani
Mital Pritmani

Reputation: 5110

Import classes conditionally with Spring Annotation

I have to import classes conditionally in my Configuration class of Spring. So there are 3 Configuration classes with @Configuration annotation:

@Configuration
public SubClass1 {
   ...
}

@Configuration
public SubClass2 {
   ...
}

@Configuration
// something like this: @Import(if (flag) 'SubClass1.class' else 'SubClass2.class')
public MainClass1 {
   ...
}

Is it possible to import classes conditionally by @import annotation? Or will I have to import all the classes?

Upvotes: 2

Views: 2677

Answers (1)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62874

As per javadoc, the value element of the @Import annotation must be an array of Class objects.

value

public abstract Class<?>[] value

The @Configuration, ImportSelector 
and/or ImportBeanDefinitionRegistrar classes to import.

Therefore, you cannot create SpEL statements to conditionally import resources using the @Import annotation.

The closest you can get to the conditional imports of resources is to use Profiles.

Upvotes: 1

Related Questions