新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

Spring Boot使用yml格式进行配置的方法,springboot application.yml 教程

发布时间:2023-08-17 07:55:31

Spring Boot使用yml格式进行配置的方法

Spring Boot使用yml格式进行配置的方法分为以下几个步骤:
1. 在项目的`src/main/resources`目录下创建一个名为`application.yml`的文件。
2. 在`application.yml`文件中使用yml格式进行配置,例如:
```yml
server:
port: 8080
servlet:
context-path: /api
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: password
jpa:
hibernate:
ddl-auto: update
show-sql: true
logging:
level:
root: INFO
com.example: DEBUG
```
3. 在Spring Boot的启动类上使用注解`@EnableAutoConfiguration`和`@SpringBootApplication`。
```java
@SpringBootApplication
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
4. 在需要读取配置的地方使用注解`@Value`或`@ConfigurationProperties`来注入配置属性。
```java
@RestController
public class ExampleController {
@Value("${server.port}")
private int serverPort;
@Value("${server.servlet.context-path}")
private String contextPath;
@GetMapping("/info")
public String getInfo() {
return "Server Port: " + serverPort + ", Context Path: " + contextPath;
}
}
```
这样,就能够使用yml格式进行配置了。在项目启动时,Spring Boot会自动读取`application.yml`文件中的配置并注入到对应的属性中。