4

springboot(6)从springboot配置文件获取值

 2 years ago
source link: https://wakzz.cn/2018/01/22/springboot/(6)%E4%BB%8Espringboot%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E8%8E%B7%E5%8F%96%E5%80%BC/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

springboot(6)从springboot配置文件获取值

祈雨的博客
2018-01-22

1、配置文件

在application.properties中添加测试数据

my.name = wxtx
my.age = 20
#my.desc的实际值为hello wxtx
my.desc = hello ${my.name}
my.host[0] = 127.0.0.1
my.host[1] = 127.0.0.2
my.host[2] = 127.0.0.3

2、获取值

@Autowired
private Environment envir;

@Value("${my.desc}")
private String desc;

@Value("${my.age}")
private Integer age;

// 不存在的值设置null
@Value("${my.history:#{null}}")
private String history;

public void testProperty() throws Exception {
//通过Environment获取值
System.out.println(envir.getProperty("my.name"));
//直接获取指定值
System.out.println(age);
System.out.println(desc);
//输出null
System.out.println(history);
}

3、依赖注入值

@Component
@ConfigurationProperties("my")
public class TestProperties {

// 自动将my.host[0]、my.host[1]、my.host[2]组装成list对象注入
private List<String> host;
public List<String> getHost() {
return host;
}
public void setHost(List<String> host) {
this.host = host;
}

}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK