Spring Import resource based on property in proper

2019-08-01 09:25发布

问题:

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.

回答1:

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;
        }
    }

}