springboot @Value 用途获取配置文件中属性比较常用
今天讲一下其常用的方法。
常用的取值方式有
- 使用占位符${}
- Spel 表达式取值#{}
- 静态变量使用set方法设置
简单示例
# springboot application.properties 文件中自定义属性
# 其中user.name spring @Value 获取的参数信息为系统变量并不是我们自定定义的数据
# 因为springboot优先从Environment中获取参数没有获取配置而文件中的配置参数
user.name=ccbobe
user.ids=1,2,3,4
user.info={"name":"ccbobe","age":28,"id":"10001"}
user.age=23
user.fullName=高山流水
使用示例
package com.ccbobe.websocket.value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@Slf4j
@RequestMapping("value")
public class ValueController {
@Autowired
private Environment environment;
@Value("${user.name}")
private String userName;
@Value("${os.name}")
private String osName;
//获取List列表
@Value("${user.ids}")
public List<Integer> ids;
// 获取数组
@Value("${user.ids}")
public Integer[] userIds;
// spel表达式获取
@Value("#{valueController.ids.get(2)}")
private Integer id;
private static String userAge;
//静态常量设置变量属性
@Value("${user.age}")
public void setUserAge(String _userAge) {
userAge = _userAge;
}
@RequestMapping("/getUserName")
public String getUserName(){
return userName + ": " +osName;
}
@RequestMapping("/getUserIds")
public Integer getUserIds(Integer index){
if (index>ids.size()-1){
return 0;
}
return ids.get(index);
}
@RequestMapping("/getUserIdByArray")
public Integer getUserIdByArray(Integer index){
return userIds[index];
}
@RequestMapping("/getUserId")
public Integer getUserId(){
return id;
}
@RequestMapping("/getStaticUserAge")
public String getStaticUserAge(){
log.info("获取到静态数据{}",userAge);
return userAge;
}
@RequestMapping("/getEnvironment")
public String getEvironment(){
log.info("获取到静态数据{}",environment);
return environment.getProperty("user.name");
}
}
如果出现乱码,需要如下处理
如果出现乱码,需要如下处理
```java
//如果不能解决就需要检查项目编码格式
@PropertySource(value = "classpath:application.properties",encoding = "utf-8")
注意事项
- 自定义变量变量使用@Value获取配置属性时,避免环境中变量属性例如 user.name、 os.name 等属性,避免不必要的困扰
- 配置文件中尽量不用中文,容易乱码,如出现乱码,其解决方案如上代码
如有问题请多多指教 : 完整代码克隆地址