如何获取application.yml文件参数
时间: 2023-08-06 13:09:46 浏览: 104
在Java Spring Boot应用程序中,可以使用@ConfigurationProperties注释和@Configuration注释创建一个配置类,以读取application.yml中的参数。首先,在application.yml文件中定义参数,例如:
```
myapp:
server:
port: 8080
database:
url: jdbc:mysql://localhost:3306/mydb
username: myuser
password: mypassword
```
然后,在Java代码中创建一个配置类,例如:
```
@Configuration
@ConfigurationProperties(prefix = "myapp")
public class MyAppConfig {
private ServerConfig server;
private DatabaseConfig database;
public static class ServerConfig {
private int port;
// getters and setters
}
public static class DatabaseConfig {
private String url;
private String username;
private String password;
// getters and setters
}
// getters and setters for server and database
}
```
现在,可以通过在Spring Bean中注入MyAppConfig来访问这些参数,例如:
```
@Service
public class MyService {
private final MyAppConfig myAppConfig;
public MyService(MyAppConfig myAppConfig) {
this.myAppConfig = myAppConfig;
}
public void doSomething() {
int port = myAppConfig.getServer().getPort();
String url = myAppConfig.getDatabase().getUrl();
String username = myAppConfig.getDatabase().getUsername();
String password = myAppConfig.getDatabase().getPassword();
// use the parameters to do something
}
}
```
这样,就可以在代码中方便地获取application.yml文件中的参数了。
阅读全文