一、System.getProperties() 获取系统环境变量
在工作中经常遇到获取系统环境变量,如获取当前资源路径、获取当前用户名等等,那如何获取所有的系统变量呢?通过System.getProperties()就可以了。
// 获取当前资源路径
System.getProperty(“user.dir”😉;
// 获取当前用户名
System.getProperty(“user.name”😉;
二、@Value注解支持属性值注入
在 Spring 组件中使用 @Value 注解的方式,可以很方便的读取 properties 文件的配置值。
@Value的属性值注入有两类:
第一个注入的是外部参数对应的property,第二个则是SpEL表达式对应的内容。
那个 default_value,就是前面的值为空时的默认值。注意二者的不同。
@Value 注解的使用场景很多,包括:
下面看看几个简单的示例:
@Value(“${username:rickie}”😉
private String userName2;
如果username 没有设置值,userName2变量值将会设置为默认值rickie。
@Value(“${user.name:tom}”😉
private String userName;
读取系统环境变量user.name,一般而言,系统环境变量user.name 都会有值,因此userName 变量将会设置为系统环境变量的值(用户名)。
@Value(“${user.age:25}”😉
private Integer age;
给包装类型Integer或者简单类型int 设置默认值。
@Value(“${some.key😮ne,two,three}”😉
private String[] stringArrayWithDefaults;
@Value(“${some.key:1,2,3}”😉
private int[] intArrayWithDefaults;
数组的默认值可以使用逗号分割。
@Value(“#{systemProperties[‘user.name’] ?: ‘default username’}”😉
private String spelWithDefaultValue;
使用 Spring Expression Language (SpEL) 设置默认值。
上面的代码表示在systemProperties中,如果没有设置 user.name 的值,my default system property value 会被设置成默认值。
使用 Spring @Value 为属性设置默认值。在项目中,提供合理的默认值,在大多情况下不用任何配置,就能直接使用。达到零配置的效果,降低被人使用的门槛。简化新Spring应用的搭建、开发、部署过程。
三、完整代码示例
下面的代码,整合了通过System.getProperties()获取系统环境变量和@Value注解注入属性值。
@RestController
public class TestController {
@Value(“${user.name:tom}”😉
private String userName;
@Value(“${username:rickie}”😉
private String userName2;
@Value(“${user.age:25}”😉
private Integer age;
@Value(“#{systemProperties[‘user.name’] ?: ‘my default system property value’}”😉
private String spelWithDefaultValue;
@RequestMapping(“/user”😉
public String simple() {
return “Hello ” + userName + “, ” + age + “!<br />”
+ “userName2: ” + userName2 + “<br />”
+ spelWithDefaultValue + “<br />”
+ getProperties();
}
private String getProperties() {
StringBuilder sb = new StringBuilder();
Properties properties = System.getProperties();
Iterator it = properties.entrySet().iterator();
while(it.hasNext()){
Map.Entry entry=(Map.Entry)it.next();
Object key = entry.getKey();
Object value = entry.getValue();
sb.append(key +”: “+value + “<br />”😉;
}
return sb.toString();
}
}
输出结果:
声明:本站部分文章内容及图片转载于互联 、内容不代表本站观点,如有内容涉及侵权,请您立即联系本站处理,非常感谢!