今天介绍三种配置文件手动取值的方式:
springboot配置文件信息保存在application.properties中,默认可以spring.开头的进行spring进行一些常用参数的配置,但是很多时候我们需要手动配置一些配置,这就需要我们自己手动取值了,
application.propertis配置文件默认存在classpath/classpaht/config中。我们也可以通过配置在启动服务器时通过启动程序时通过手动配置参数置顶该路径,这里就暂时不做演示,今天主要学习的是如何取得配置文件中的值。
方式1:
通过 SpringApplication.run(Application.class, args);返回的上下文信息ConfigurableApplicationContext取的
Environment,然后通过getProperty(key);取得value,直接上代码:
配置文件key-value:
1
|
server.host=
127.0
.
0.1
|
java代码:
1
2
|
ConfigurableApplicationContext context = SpringApplication.run(Application.
class
, args);
context.getEnvironment().getProperty(
"server.host"
);<br>System.out.println(
"post"
+ context.getEnvironment().getProperty(
"server.host"
));<br>
|
输出信息:
这里的Environment也可以通过
@Autowired
Environment env;
自动装配。
方式2:
通过@Value("${key}")取值,
配置文件key-value:
1
|
server.post=
8080
|
java代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
package
com.wangx.springboot.controller;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.beans.factory.annotation.Value;
import
org.springframework.core.env.Environment;
import
org.springframework.stereotype.Component;
/**
* 取值
* @author Administrator
*
*/
@Component
(
"users"
)
public
class
User {
@Value
(
"${server.post}"
)
private
String post;
public
void
print() {
System.out.println(post);
}
}
|
Applilcation.java
1
2
|
User user = (User)context.getBean(
"users"
);
user.print();
|
控制台输出:
方式3:
在配置文件中通过${key}引用配置信息
配置文件:
name=springboot
server.name=this is a ${name}
User.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
package
com.wangx.springboot.controller;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.beans.factory.annotation.Value;
import
org.springframework.core.env.Environment;
import
org.springframework.stereotype.Component;
/**
* 取值
* @author Administrator
*
*/
@Component
(
"users"
)
public
class
User {
@Autowired
Environment env;
@Value
(
"${server.name}"
)
private
String post;
public
void
print() {
System.out.println(post);
}
}
|
控制台信息:
‘
OK,三次取值 演示完毕。