Springboot读取配置文件
时间: 2023-07-18 09:08:38 浏览: 122
在Spring Boot中,可以通过@ConfigurationProperties注解读取配置文件中的属性值。具体步骤如下:
1.在application.properties或application.yml文件中添加需要读取的属性值,例如:
application.properties:
```
myapp.name=My Application
myapp.version=1.0.0
```
application.yml:
```
myapp:
name: My Application
version: 1.0.0
```
2.在配置类中添加@ConfigurationProperties注解,并指定prefix为配置文件中的前缀,例如:
```
@Configuration
@ConfigurationProperties(prefix = "myapp")
public class MyAppConfig {
private String name;
private String version;
// 省略getter和setter方法
}
```
3.在启动类中添加@EnableConfigurationProperties注解,并将配置类作为参数传入,例如:
```
@SpringBootApplication
@EnableConfigurationProperties(MyAppConfig.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
4.在需要使用属性值的地方注入配置类,并通过getter方法获取属性值,例如:
```
@Service
public class MyService {
private final MyAppConfig myAppConfig;
public MyService(MyAppConfig myAppConfig) {
this.myAppConfig = myAppConfig;
}
public void doSomething() {
String name = myAppConfig.getName();
String version = myAppConfig.getVersion();
// ...
}
}
```
阅读全文