我想评估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')}
Run Code Online (Sandbox Code Playgroud)
但是,为了systemProperties['os.name']每次评估,我想在变量中使用它,然后想要匹配条件.我看到了#this变量用法(http://docs.spring.io/spring-framework/docs/3.0.6.RELEASE/spring-framework-reference/html/expressions.html sec 6.5.10.1)并尝试制作以下内容SPEL
#{systemProperties['os.name'].?((#this.indexOf('nix') >= 0 or #this.indexOf('nux') >= 0 or #this.indexOf('aix') > 0 ) ? 'unix' :
(#this.indexOf('win') >= 0) ? 'windows' : 'Unknown')}
Run Code Online (Sandbox Code Playgroud)
但不知何故,它正在给出解析异常.
有人可以提出任何建议吗?
我会说,这种方法怎么样,更优雅.需要春天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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用上面的条件来根据环境注释要加载的所需方法或类:
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
linux.xml:
<context:property-placeholder location="classpath:/META-INF/spring/linux.properties" />
Run Code Online (Sandbox Code Playgroud)
windows.xml:
<context:property-placeholder location="classpath:/META-INF/spring/windows.properties" />
Run Code Online (Sandbox Code Playgroud)
也许它可以进一步增强,但只是想向您展示根据操作系统使用某些xml文件的另一个想法.
| 归档时间: |
|
| 查看次数: |
1261 次 |
| 最近记录: |