Spring Import resource based on property in proper

2019-08-01 09:24发布

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条回答
仙女界的扛把子
2楼-- · 2019-08-01 09:47

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

}
查看更多
登录 后发表回答