# 1.读取核心配置文件
核心配置文件是指在 `resources` 根目录下的 `application.properties` 或 `application.yml` 配置文件,读取这两个配置文件的方法有两种,都比较简单。
核心配置文件 `application.properties` 内容如下:
```bash
server.port=9090
test.msg=Hello World Springboot!
```
# 2.使用``@Value``方式(常用):
```java
@RestController
public class WebController {
@Value("${test.msg}")
private String msg;
}
```
**注意**:在 `@Value` 的 `${}` 中包含的是核心配置文件中的键名。
对于静态变量无法使用``@Value``赋值,可以曲线救国:
```java
@Component
public class FileUtils {
private static String location;
// 静态变量可以这样注入配置值
@Value("${xxx.location}")
public void setLocation(String location) {
FileUtils.location = location;
}
}
```
# 3.使用Environment方式
```java
@RestController
public class WebController {
@Autowired
private Environment env;
@RequestMapping(value = "index", method = RequestMethod.GET)
public String index2() {
return env.getProperty("test.msg");
}
}
```
注意:这种方式是依赖注入 `Evnironment` 来完成,使用 `@Autowired` 注解即可完成依赖注入,然后使用 `env.getProperty("key")` 即可读取出对应的值。
# 4.读取自定义配置文件
例如在 `resources/conf` 目录下创建配置文件 `sherlocky.properties` 文件内容如下:
```bash
sherlocky.name=sherlock
sherlocky.version=1.0.0
...
```
需要一个管理配置的实体类:
```java
@ConfigurationProperties(locations = "classpath:conf/sherlocky.properties", prefix = "sherlocky")
@Component
public class MyWebConfig {
private String name;
private String version;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
```
**注意**:`@ConfigurationProperties` 注解有两个属性:
* ==locations==:指定配置文件的所在位置
* ==prefix==:指定配置文件中键名称的前缀
该类添加了 `@Component` 注解,就可以使用 `@Autowired` 将该配置类注入到别的类使用。
## 4.1 绑定属性配置
**注意:**``@ConfigurationProperties``注解并没有把当前类注册成为一个 Spring 的 Bean,将其注入大致有三种方式:
- 1.配合使用``@Component``注解直接进行注入。
```java
@ConfigurationProperties(prefix = "sherlocky")
@Component
public class SherlockyProperties {
// 代码...
}
```
- 2.使用``@EnableConfigurationProperties``注解,通常配置在标有``@Configuration``的类上,当然其他``@Component``注解的派生类也可以,不过不推荐。
```java
@ConfigurationProperties(prefix = "sherlocky")
public class SherlockyProperties {
// 代码...
}
```
```java
@EnableConfigurationProperties(SherlockyProperties.class)
@Configuration
public class SherlockyConfiguration {
// 代码...
}
```
- 3.使用``@Bean``方式在标有``@Configuration``的类中进行注入,这种方式通常可以用在对第三方类进行配置属性注册的情况。
```java
public class SherlockyProperties {
// 代码...
}
```
```java
@Configuration
public class SherlockyConfiguration {
@ConfigurationProperties("sherlocky")
@Bean
public SherlockyProperties sherlockyProperties() {
return new SherlockyProperties();
}
}
```
---
参考:[Spring Boot 2.0 @ConfigurationProperties 使用](https://segmentfault.com/a/1190000016941757?utm_source=tag-newest)
Spring Boot学习1——配置文件