用于评估OS的Spring表达式

时间:2014-04-29 06:06:05

标签: spring

我想评估OS(操作系统)系统属性来加载环境对应的配置文件。例如。如果操作系统评估为Windows,则properties-win.xml将加载,如果操作系统评估为Unix或Linux,则将加载properties-unix.xml

以下拼写正常

#{(systemProperties['os.name'].indexOf('nix') >= 0 or systemProperties['os.name'].indexOf('nux') >= 0 or systemProperties['os.name'].indexOf('aix') > 0 ) ? 'linux' : 
        ((systemProperties['os.name'].indexOf('Win') >= 0) ? 'windows' : 'Unknow OS')}

但是每次评估systemProperties['os.name']时,我想在变量中使用它,然后想要匹配条件。 我看到#this变量用法(http://docs.spring.io/spring-framework/docs/3.0.6.RELEASE/spring-framework-reference/html/expressions.html秒6.5.10.1),并尝试制作以下拼写

#{systemProperties['os.name'].?((#this.indexOf('nix') >= 0 or #this.indexOf('nux') >= 0 or #this.indexOf('aix') > 0 ) ? 'unix' : 
    (#this.indexOf('win') >= 0) ? 'windows' : 'Unknown')}

但不知何故,它给出了解析异常。

有人可以提出任何建议吗?

2 个答案:

答案 0 :(得分:5)

我会说,这种方法怎么样,更优雅。需要春天4。

public class WindowsEnvironmentCondition implements Condition {
     public boolean matches(ConditionContext context,AnnotatedTypeMetadata metadata) {
          return context.getEnvironment().getProperty("os.name").indexOf("Win") >= 0;
     }
}

public class LinuxEnvironmentCondition implements Condition {
     public boolean matches(ConditionContext context,AnnotatedTypeMetadata metadata) {
          return (context.getEnvironment().getProperty("os.name").indexOf("nux") >= 0 
                 || context.getEnvironment().getProperty("os.name").indexOf("aix") >= 0);
     }
}

然后你可以使用上面的Conditions来注释要加载的所需方法或类,具体取决于环境:

@Configuration
@Conditional(LinuxEnvironmentCondition.class)
@ImportResource("classpath:/META-INF/spring/linux.xml")
public class LinuxConfig {

private @Value("${test}") String message;

public @Bean
ExampleService service() {
    ExampleService service = new ExampleService();
    service.setMessage(message);
    return service;
}
}

@Configuration
@Conditional(WindowsEnvironmentCondition.class)
@ImportResource("classpath:/META-INF/spring/windows.xml")
public class WindowsConfig {

private @Value("${test}") String message;

public @Bean
ExampleService service() {
    ExampleService service = new ExampleService();
    service.setMessage(message);
    return service;
}
}

linux.xml:

<context:property-placeholder location="classpath:/META-INF/spring/linux.properties" />

windows.xml:

<context:property-placeholder location="classpath:/META-INF/spring/windows.properties" />

也许它可以进一步增强,但只是想向您展示根据操作系统使用某些xml文件的另一个想法。

答案 1 :(得分:2)

无法在Spel表达式中设置变量。必须将变量设置为上下文。你可以这样做

context.setVariable("os", SystemProperties.getProperty("os.name")); 

然后在你的Spel中使用它作为#os

相关问题