Sohan Soni
Sohan Soni

Reputation: 1238

Spring Import resource based on property in properties file - without using spring profile - Conditional Context Loading

I want to import the resource based on value of property in properties file, there are several context files and spring should load only those whose value is set to true. These values are different for different customers.

<import if{property} = true resource="classpath*:prod-config.xml"/>

and I can't use spring profiles here. Please suggest.

Upvotes: 1

Views: 3590

Answers (1)

codependent
codependent

Reputation: 24472

You can use Spring 4's Conditionals to achieve that behaviour

For instance:

@Configuration
@Conditional(MyConditionalProd.class)
@ImportResource("classpath*:prod-config.xml")
public class MyConditionalProdConfig {}

MyConditionalProd would implement the conditional logic:

public class MyConditionalProd implements ConfigurationCondition{

    @Override
    public ConfigurationPhase getConfigurationPhase() {
        return ConfigurationPhase.PARSE_CONFIGURATION;
    }

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String property = context.getEnvironment().getProperty("someProperty");
        if("prod".equals(property)) {
            return true;
        }else{
            return false;
        }
    }

}

Upvotes: 2

Related Questions